Smalltalk: adding new methods to existing classes
New methods added to the Integer class:
----------------------------------------
mymax: x
"returns the larger of x and receiver"
x > self ifTrue: [^ x].
^ self
sumUpTo
"returns the sum of the numbers from 1 up to the receiver"
| sum |
sum := 0.
(1 to: self) do: [:x | sum := sum + x].
^ sum
sumUpToRec
"returns the sum of the numbers from 1 up to the receiver, recursive version"
"sample calls:"
"5 sumUpToRec"
"100 sumUpToRec"
self <= 0 ifTrue: [^ 0].
^ self + ((self - 1) sumUpToRec)
myfactorial
"returns the factorial of the receiver, recursive version"
"sample call:"
"7 myfactorial"
self <= 0 ifTrue: [^ 1].
^ self * ((self - 1) myfactorial)
New method added to the Object class:
-------------------------------------
print
"show the receiver in the Transcript"
Transcript show: self; cr.