[Haskell-beginners] Chain computations
Tim Baumgartner
baumgartner.tim at googlemail.com
Sat Nov 20 13:32:16 EST 2010
Thanks Brent,
I think I understood your point: In my form a ->> f ->> g, there are
parentheses like (a ->> f) ->> g, and the parenth expression resolves
to a value, whereas in a >$> f >>> g, there are parentheses like a >$>
(f >>> g), and the parenth expression is a function which is much more
flexible.
Tim
2010/11/20 Brent Yorgey <byorgey at seas.upenn.edu>:
> 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
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
More information about the Beginners
mailing list