Skip to content

Instantly share code, notes, and snippets.

@knewter
Created August 24, 2013 15:39
Show Gist options
  • Save knewter/6328807 to your computer and use it in GitHub Desktop.
Save knewter/6328807 to your computer and use it in GitHub Desktop.
Elixir anonymous function recursion
calculate_bill = fn
{:item, price} -> price
[h|t] -> calculate_bill.(h) + calculate_bill.(t)
end
calculate_bill.([{:item, 20}, {:item, 10}])
calculate_bill.({:item, 35})
# It should also work with a list of more than two elements:
calculate_bill.([{:item, 20}, {:item, 10}, {:item, 35}])
iex(17)> calculate_bill.([{:item, 20}, {:item, 10}])
** (UndefinedFunctionError) undefined function: IEx.Helpers.calculate_bill/1
IEx.Helpers.calculate_bill({:item, 10})
erl_eval.erl:569: :erl_eval.do_apply/6
erl_eval.erl:395: :erl_eval.expr/5
erl_eval.erl:396: :erl_eval.expr/5
src/elixir.erl:147: :elixir.eval_forms/3
iex(17)> calculate_bill.({:item, 35})
35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment