Skip to content

Instantly share code, notes, and snippets.

@bodhi
Last active May 22, 2018 15:39
Show Gist options
  • Save bodhi/cc4f3ac32d8302de2a8b to your computer and use it in GitHub Desktop.
Save bodhi/cc4f3ac32d8302de2a8b to your computer and use it in GitHub Desktop.
Implementation of Elixir's pipeline operator `|>` in Haskell

Elixir's pipeline operator |> apparently passes the result of each step as the first parameter to the next, so

iex> [1, [2], 3] |> List.flatten |> Enum.map(fn x -> x * 2 end)
[2, 4, 6]

is equivalent to

iex> Enum.map(List.flatten([1,[2],3]), fn x -> x * 2 end)
[2, 4, 6]

Which is function composition, but the partial application happens from the left (first parameter).

"Equivalent" in Haskell:

[[1,2],[2,3],[3,4]] |> flatten |> map (\x -> x * 2)
[2,4,4,6,6,8]

(scare quotes as we can't have a mixed list [1,[2],3] as in the Elixir example)

(|>) :: a -> (a -> b) -> b
a |> b = b a
flatten :: [[a]] -> [a]
flatten = foldl (++) []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment