Skip to content

Instantly share code, notes, and snippets.

@alco
Created September 18, 2014 09:42
Show Gist options
  • Save alco/e19603cb07bacdb8834a to your computer and use it in GitHub Desktop.
Save alco/e19603cb07bacdb8834a to your computer and use it in GitHub Desktop.
defmodule Compositions do
# "Call" composition
#
# f = Enum.map(& &1+1) ||| Enum.reverse
#
# f.([1,2,3]) #=> [4, 3, 2]
#
# g = f.() ||| List.to_tuple
#
# g.([1,2,3]) #=> {4, 3, 2}
#
defmacro c1 ||| c2 do
quote do
fn x ->
x |> unquote(c1) |> unquote(c2)
end
end
end
# Function composition
#
# ff = fn x -> Enum.map(x, & &1+1) end >>> &Enum.reverse/1
#
# ff.([1,2,3]) #=> [4, 3, 2]
#
# gg = ff >>> &List.to_tuple/1
#
# gg.([1,2,3]) #=> {4, 3, 2}
#
defmacro f1 >>> f2 do
quote do
fn x ->
unquote(f2).(unquote(f1).(x))
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment