I can write an anonymous function in the interactive shell directly like below.
iex> total_bottles_milk = fn total -> total * 2 end
iex> total_bottles_milk.(2)
However, if I write in an external file and run in the interactive shell, it shows a Compile Error.
My file name and directory path is lib/expense.ex
Below is my code
defmodule Expense do
total_bread_slices = fn total -> (total * 10) / 100 end
total_bottles_milk = fn total -> total * 2 end
total_cakes = fn total -> total * 15 end
def total_expense(bread_slices, bottles_of_milk, cakes) do
total_bread_slices.(bread_slices) + total_bottles_milk.(bottles_of_milk) + total_cakes.(cakes)
end
end
When I go into the folder path and run iex -S mix
to run my Expense module, terminal shows Compilation error.
I'm wondering only I can run anonymous function directly into the interactive shell and not from external sources and compile it. I want to write my function as a first-class citizen. And if there is a way, how can I do it?
def total_cokes(total), do: total * 15
and then create an anonymous function by doing&total_cokes/1
. Returning anonymous functions from within normal functions (like your answer) is not idiomatic.