Confusing issue with blocks

Boris Gaertner Boris.Gaertner at gmx.net
Tue Dec 12 20:37:41 UTC 2006


From: "J J" <azreal1977 at hotmail.com> wrote:


> Hi all,
>
> I am having a strange problem with anonymous blocks.
>
> I read on the list that the solution to this problem is to copy or clone
the
> block.
Yes, that is a good advice.

> I have enclosed the file out of the Lazy list classes (it's not a lot of
> code), I would appreciate any help anyone could give me.
With that code it is not too difficult to understand what you are
doing.

The problem with our good old Squeak is that blocks cannot be used
recursively. To see that problem. evaluate:

  | fac |

  fac := [:int | int = 1 ifTrue: [1]
              ifFalse: [int* (fac value: int - 1)]
      ].
  fac value: 2

You will get exactly the error message that you got with your
code.

When you do this:
  | fac |

  fac := [:int | int = 1 ifTrue: [1]
              ifFalse: [int* (fac clone value: int - 1)]
      ].
  fac clone value: 5

you will get the expected result.


In your code, you should modify method
LazyElement>> inject:into:

inject: aValue into: aBinaryBlock
 "NOTE: This method does not behave as a normal
  inject into.  It actually behaves exactly like fold_right"

 ^ aBinaryBlock clone   " <-  clone here "
       value: head
       value: (LazyValue delay: [ tail force inject: aValue into:
aBinaryBlock])

That should help.


A slightly different approach introduces an instance method
that creates a block instance:

flattenBlock

   ^[:p :e| p append: e ]

and modifies methods flatten and inject:into:

flatten

 ^ self inject: LazyNil new into: [self flattenBlock]


inject: aValue into: aBinaryBlockGenerator
 "NOTE: This method does not behave as a normal inject into.  It actually
behaves exactly like fold_right"

 ^ aBinaryBlockGenerator value "  this value calls a block that creates
                             a new block instance "
     value: head
      value: (LazyValue delay: [ tail force inject: aValue into:
aBinaryBlockGenerator])

> Thanks,
> Jason

I know that this is tricky stuff, but I also hope that my remarks
are to some extent helpful.

Greetings,
Boris




More information about the Squeak-dev mailing list