Re: Difference between method and block - with examples
Shashank Date <[email protected]>
| Newsgroups | gmane.comp.lang.io |
|---|---|
| Message-ID | <[email protected]> |
Hi,
> You can use them like you would in any language but be aware that like in any other language,
> blocks retain the stack which they reference - so only use them if that's what you want.
I am afraid I do not understand what you mean by "blocks retain the stack which they refer"
>Here's an example of implementing a Smalltalk like ifTrue method with blocks:
>
>true ifTrue := method(a, a call; self)
>true ifFalse := method (a, self)
>false ifTrue := method(a, self)
>false ifFalse := method (a, a call; self)
>
>example use:
>
>foo ifTrue(block(x := 1))
Ok ... got that part.
>Though it's terser to do:
>
>if(foo, x := 1)
It may be terser but does not seem to be equivalent. While as
"foo ifTrue(block(x := 1))" will not make x available to the outer context, the expression "if(foo, x:= 1)" will!
> Note that unlike most other languages, we don't need to use blocks for control flow in Io since
> all arguments are passed as expressions and the receiver can determine if/how to eval them.
> Likewise, we also don't need conventional macros since we have far more control over evaluation than macros offer.
I see. I was trying to understand the documentation which says:
"A block is the same as a method except it is lexically scoped. That is,
variable lookups continue in the context of where the block was created
instead of the target of the message which activated the block."
Based on what I know of lexically scoped closure, I was expecting something like this in Ruby:
n = 10
blk = lambda{|i| i + n}
blk.call(2) # returns 12
To translate into Io as:
n := 10
blk := block(i, i + n)
blk call 2 # Exception: nil does not respond to '+'
Am I missing some salient point?
Thanks,
- Shashank