Discussion:
Why this code works?
w***@gmail.com
2014-11-23 00:53:28 UTC
I encountered this code:

BlockClosure extend [
times: count [
(count = 0)
ifTrue: [^self value]
ifFalse: [self value. ^self time: count - 1]
]
].

x := 5.

[x := x - 1] time: 3 .

x printNl.

This gives me 1. I know this uses recursion to achieve iteration. But I wonder why the count which is a constant (3) here, can be decremented each time of iteration?

Another question is why do we need the "self value" in the "ifFalse" block. If I remove it, it then seems that there is no iteration. The block [x := x-1] executed one time and then stopped. Do anyone know the answers to these questions? Thanks
s***@yahoo.ie
2014-12-02 13:08:09 UTC
Iteration 1
pre: x := 5. count := 3
post: [x := x - 1] executed once. x:=4. count :=2

Iteration 2
pre: x := 4. count := 2
post: [x := x - 1] executed once. x:=3. count :=1

Iteration 3
pre: x := 3. count := 1
post: [x := x - 1] executed once. x:=2. count :=0

Iteration 4
pre: x := 2. count := 0
post: [x := x - 1] executed once. x:=1. count :=0

self value in false block ensures that the block ([x := x - 1]) is in fact executed.
Post by w***@gmail.com
BlockClosure extend [
times: count [
(count = 0)
ifTrue: [^self value]
ifFalse: [self value. ^self time: count - 1]
]
].
x := 5.
[x := x - 1] time: 3 .
x printNl.
This gives me 1. I know this uses recursion to achieve iteration. But I wonder why the count which is a constant (3) here, can be decremented each time of iteration?
Another question is why do we need the "self value" in the "ifFalse" block. If I remove it, it then seems that there is no iteration. The block [x := x-1] executed one time and then stopped. Do anyone know the answers to these questions? Thanks