Wednesday, June 22, 2011

10 Smalltalk One Liners to Impress Your Friends

Some days ago, Antonio posted a list of 10 Ruby one-liners. The 1-liners saga started with

  Scala,

    then

      CoffeeScript,

       Haskell,

         Clojure,

           Python,

             Groovy

Very good, everyone wants to impress his friends, perhaps She could impress your friends more. Anyway, the grandaddy of programming languages, Smalltalk, is alive even if its voice is weak.

So, let's start

Multiply each item in a list by 2
(1 to: 10) collect:  [:each | each * 2]


Sum a list of numbers
(1 to: 1000) inject: 0 into: [:sum :each | sum + each]


Verify if tokens exist in a string
words := {'smalltalk'. 'akka'. 'play framework'. 'sbt'. 'typesafe'}.
tweet := 'This is an example tweet talking about smalltalk and sbt'.
words anySatisfy: [:each | tweet includesSubString: each]

but Collection>>detect: is more speaking and you can have the first occurrence back

words := {'smalltalk'. 'akka'. 'play framework'. 'sbt'. 'typesafe'}.
tweet := 'This is an example tweet talking about smalltalk and sbt'.
words detect: [:each |tweet includesSubString: each]


Reading a file
(FileStream fileNamed:'test.txt') contents.
Wonderful.


Happy Birthday
Transcript show:'Happy Birthday to You\Happy Birthday to You\Happy Birthday dear Davide\Happy Birthday to You' withCRs
Less geeky than the Scala ex., but more simple and communicative ;-)


Filter a list of numbers
#(49 58 76 82 88 90) groupedBy: [:n| n > 60] 


Fetch and parse an XML web service
XMLDOMParser parseDocumentFrom:(HTTPSocket httpGet:'search.twitter.com/search.atom?&q=smalltalk')



Find minimum (or maximum) in a list
#(49 58 76 123 82 88 90 -3) max
#(49 58 76 123 82 88 90 -3) min


Parallel Processing
Hmm, there isn't an easy way, you should use a specific VM such as:
Polycephaly or RoarVM, but I have no direct experience on them


Sieve of Eratosthenes
sieve := Array new: aNumber withAll: true. 
sieve at: 1 put: false. 
2 to: aNumber do: [:i | (sieve at: i) ifTrue: [2*i to: aNumber by: i do: [:k | sieve at: k put: false] ] 

That's a snippet I posted some years ago. It's not a one liner, but like Antonio I think it's readable.


First Bonus! - Size of running objects
Array allInstances size 
You can see, it's easy to find all instances of an object and calculate their total size.


Second Bonus! - Fast code cleanup
SystemNavigation new allUnsentMessages
Calling allUnsentMessages you can find all methods none call. Sigh, they are very very sad, nobody is interested in them, you should clean up your code :-)

See you next time!