[squeak-dev] Collection's #fold: vs #reduce:

Eliot Miranda eliot.miranda at gmail.com
Tue Nov 2 20:32:20 UTC 2010


On Tue, Nov 2, 2010 at 1:23 PM, Juan Vuletich <juan at jvuletich.org> wrote:

> Nicolas Cellier wrote:
>
>>
>> I'd say which selector are implemented in Pharo and Cuis ?
>> We should better converge.
>>
>> Nicolas
>>
>>
>
> Hi folks,
>
> Cuis doesn't include any of them yet. I can add whatever people prefer.
> What I'd do different is the implementation:
>
> fold: aBinaryBlock
>
>   "Evaluate the block with the first two elements of the receiver,
>    then with the result of the first evaluation and the next element,
>    and so on.  Answer the result of the final evaluation. If the receiver
>    is empty, raise an error. If the receiver has a single element, answer
>    that element."
>   "
>   #('if' 'it' 'is' 'to' 'be' 'it' 'is' 'up' 'to' 'me') fold: [:a :b | a, '
> ', b]
>   "
>   | noPreviousValue |
>   noPreviousValue := Object new.    "something that can't be in the
> receiver"
>   ^self inject: noPreviousValue into: [ :previousValue :each |
>       previousValue == noPreviousValue
>           ifTrue: [ each ]
>           ifFalse: [ aBinaryBlock value: previousValue value: each ]]
>
> This is easier to understand, and it also makes clear the relation between
> #fold: (or #reduce:) and #inject:into: .
>

I disagree.   inject:into: is not particularly easy to understand, whereas
both the existing fold: and reduce: are understandable in terms of do:. Also
the use of inject:into: isn't really buying you anything since the logic in
the block within the inject:into: usage is as complex as that within fold:
or reduce:. Further, this /is/ a lot slower because of the extra level of
evaluation (there's an extra block activation around each element).


best,
Eliot


> Cheers,
> Juan Vuletich
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.squeakfoundation.org/pipermail/squeak-dev/attachments/20101102/6da9bc46/attachment.htm


More information about the Squeak-dev mailing list