How to impress the locals...

Chris Schreiner chris.schreiner at online.no
Sat Jul 16 22:04:01 UTC 2005


Feed us! :-)

Alan Lovejoy wrote:

> It’s always fun to show non-Smalltalkers some of the neat stuff one 
> can do with Smalltalk. One of my favorite set of examples involves 
> #inject:into:.
>
> The canonical example is of course something like `#(8 1 6) inject: 0 
> into: [:total :value | total + value].`
>
> But you shouldn’t stop there, because a) “the locals” often have some 
> sort of summation function available in their favorite language that, 
> they think, “does the same thing,” and b) because there are many much 
> better examples (and these are good to keep in mind when coding.) The 
> canonical example is really only useful for explaining the basic 
> concept (and perhaps clarifying points of Smalltalk syntax and/or 
> semantics.) Then comes the advanced course:
>
> 1. Concatenation
>
> #(‘usr’ ‘local’ ‘bin’) inject: ‘’ into: [:path :suffix | path, ‘/’, 
> suffix].
>
> 2. Min/max:
>
> #(9 2 4 12 -3 44) inject: Infinity positive into: [:min :value | value 
> >= min ifTrue: [min] ifFalse: [value]]
>
> #(9 2 4 12 -3 44) inject: Infinity negative into: [:max :value | value 
> <= max ifTrue: [max] ifFalse: [value]]
>
> If your image doesn’t have Infinity:
>
> #(9 2 4 12 -3 44) inject: nil into: [:min :value | (min == nil or: 
> [value < min]) ifTrue: [value] ifFalse: [min]]
>
> 3. Hierarchical path traversal:
>
> “Note: this is a really good technique for representing and traversing 
> namespace paths in a syntax-independent way”
>
> #(TextConstants CR) inject: Smalltalk into: [:poolDictionary :key | 
> poolDictionary at: key]
>
> #(HKEY_CURRENT_USER ENVIRONMENT TZ)
>
> inject: WindowsRegistry current
>
> into: [:namespace :key | namespace at: key]
>
> | path |
>
> path := #(home alan smalltalk squeak `3.9’ alan.image)
>
> inject: ResourcePath root
>
> into: [:path :suffix | path exists ifFalse: [path makeDirectory]. 
> path, suffix].
>
> path exists ifTrue: [path execute].
>
> Of course, some of the above examples assume the existence of certain 
> classes that you probably don’t have in your image. Perhaps you should…
>
> --Alan
>
>------------------------------------------------------------------------
>
>
>  
>




More information about the Squeak-dev mailing list