How do I define a function?

From Cuis CookBook
Jump to navigation Jump to search
  • Most probably, if you asked yourself how do I define a function ... it is because you are very new to Smalltalk. You need to know straight now that defining a function as we will do now is very much infrequent in Smalltalk since out credo is: The world is made of objects and actions are carried out sending messages to object. Therefore, every time you think I should define a function you should instead be thinking I should define a proper method !
  • Here is how you define and use the simplest function in Smalltalk, we call them BlockClosure.
f := [ :x | x * 2]. 
f class.           "=>" BlockClosure 
f value: 5.        "=>" 10
  • Do you want to get more sophisticated ? Here is a 2 arguments function
g := [ :x :y | x + y ]. 
g value: 3 value: 5.     "=>" 8


  • Do you now want to do the right thing ? Then, learn how to define the message double inside the class Number.