Skip to content

Instantly share code, notes, and snippets.

@tapickell
Created August 1, 2024 17:33
Show Gist options
  • Save tapickell/80da536037ea5c93de3ec8679e6dda06 to your computer and use it in GitHub Desktop.
Save tapickell/80da536037ea5c93de3ec8679e6dda06 to your computer and use it in GitHub Desktop.
defmodule Composition do
@identity fn x -> x end
def compose([]), do: @identity
def compose([f]) when is_function(f), do: f
def compose([f, g]) when is_function(f) && is_function(g) do
fn
[] -> f.(g.())
args when is_list(args) -> f.(g.(args))
end
end
def compose(functions) when is_list(functions) do
reduce(functions, &comp/1)
end
def compose_ltr([]), do: @identity
def compose_ltr([f]) when is_function(f), do: f
def compose_ltr([f, g]) when is_function(f) && is_function(g) do
fn
[] -> g.(f.())
args when is_list(args) -> g.(f.(args))
end
end
def compose_ltr(functions) when is_list(functions) do
reduce(functions, &comp/1)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment