[Haskell-beginners] Chain computations

Brent Yorgey byorgey at seas.upenn.edu
Sat Nov 20 12:33:41 EST 2010


On Sat, Nov 20, 2010 at 06:10:22PM +0100, Tim Baumgartner wrote:
> Hi,
> 
> I really like fooling around with operators. In elementary school, we
> always had to make chain computations, e.g.
> 
> teacher: 2
> teacher: +1
> teacher: *2
> teacher: divided by 3
> 
> Again, I didn't find the following operator on hoogle (very similar to ($)):
> (->>) :: a -> (a -> b) -> b
> a ->> f = f a

You can define (->>) as flip ($).

> 
> Using it, we can nicely write down the above computation:
> 2 ->> (+1) ->> (*2) ->> (`div` 3)

Another way to write this is using (>>>) from Control.Category which
is essentially flipped function composition.  Occasionally I will
write things in this style and define (>$>) to be the same as your
(->>), and write things like

  2 >$> (+1) >>> (*2) >>> (`div` 3)

If we did the same thing in right-to-left style, your code would
correspond to

  (`div` 3) $ (*2) $ (+1) $ 2

whereas mine corresponds to

  (`div` 3) . (*2) . (+1) $ 2

The latter is generally considered better style, since any subsection
of the "pipeline" on the left side of the $ is valid on its own,
making it much easier to refactor (pull out pieces of the pipeline
that are also used elsewhere and give them a name, and so on).  Also,
this form makes it clear that the 2 at the end is different.  Simply
removing the $ 2 gives a valid function that abstracts away from the
specific starting value and will work for any starting value.

-Brent


More information about the Beginners mailing list