inject into (was RE: Message Eating Null - article)

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

inject into (was RE: Message Eating Null - article)

J J-6

Ah, I see.  Well not being able to read code because it uses concepts that are currently alien to you is quite different then not being able to read code because it looks like cursing cartoon characters. :)

There are basically 3 things you can do do a list of entities: (1) you can *transform* it to some other kind of list (i.e. #collect in Smalltalk, map in most functional languages), (2) you can *filter* it (i.e. #select/#reject in Smalltalk, filter in most functional languages) and (3) you can *reduce* it (i.e. #inject:into: in Smalltalk, foldl/foldr in most functional languages).

The interesting thing about the reduction is that all other traversals can be expressed with it.  But, as you mentioned, reduction is the hardest of the others to understand at first.

For me the easiest way to understand it is if you imagine a list #(1 2 3 4 5) can also be expressed as 1 : 2 : 3 : 4 : 5 : [], where : means cons the left hand side value onto the front of the list on the right hand side.  So 5 : [] is the same as #(5).  The list is built from right to left so the above two lists are equivalent.

Now, what a fold does is it replaces every : with a function and the [] with the value you supply.  So if we wanted to sum the above numbers we can say:   #(1 2 3 4 5) inject: 0 into: [:a :b | a + b].  This changes the list 1 : 2 : 3 : 4 : 5 : [] into 1 + 2 + 3 + 4 + 5 + 0.

Now, what I said is true for foldl and foldr (the difference between those two functions is just which side do you start adding them up, going left or going right), but #inject:into (a right fold) has the difference that it injects the value into the *front* instead of the end.  But this is probably what you want most cases for an OO language where the inserted value is likely the object you want the list to reduce on.



> Date: Thu, 26 Jul 2007 20:54:20 +0100

> From: [hidden email]
> To: [hidden email]
> Subject: Re: Message Eating Null - article
>
>
> >
> > > > widget setStringValue: #(office phone lastNumberDialed asString)
> > > > inject: person into: [:obj :sel| o == nil ifTrue: [ nil ] ifFalse: [
> > > > obj sel ] ]
> > >
>
> Not being that clever, I find #inject:into: to be the most obfuscated
> message in the image. Whenever I see it I have to think quite hard to
> work out what is going on.
>
> I was confused long before I got to the block.
>
> The original code has the advantage that it works without me needing to
> know how exactly the effect is achieved.
>
> cheers
>
> Keith
>


See what you’re getting into…before you go there. Check it out!