Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell function composition (forward pipe) - why does this work?

Tags:

In the below code, fibseq represents a sequence of numbers from the Fibonacci sequence. (from code to solve Project Euler #2)

I have defined an infix function |>:

(|>) x y = y x.

This lets me do the following (like a unix pipeline):

take 34 fibseq |> filter even |> filter (< 4000000) |> sum

My question is, why does this work?

I would have thought that take 34 fibseq |> filter even ought to transform into filter (take 34 fibseq) even, which (I think) would lead to a type error.

Instead it seems to be transforming into filter even (take 34 fibseq) which works and is what I want, but I don't understand why it's working.

like image 468
sea6ear Avatar asked Jul 23 '10 20:07

sea6ear


1 Answers

Function application (like filter even) binds tighter than any operators, so your code is equivalent to:

(take 34 fibseq) |> (filter even) |> (filter (< 4000000)) |> sum
like image 162
sth Avatar answered Nov 06 '22 19:11

sth