I am new to elixir and I am trying to make a recursive anonymous function, but for some reason my anynymous function that works on it's own as expected throws me "2nd argument: not valid character data (an iodata term)" error.
Here is code:
calcTip = fn bill ->
if bill >= 50 and bill <= 300, do: bill * 0.15, else: bill * 0.2
end
bills = [ 22, 295, 176, 440, 37, 105, 10, 1100, 86, 52 ]
calcTipsAndTotals = fn index, tips, totals, recursiveFn ->
case index < length(bills) do
true ->
new_tip = calcTip.(Enum.at(bills, index, 0))
new_tips = tips ++ [new_tip]
new_totals = totals ++ [Enum.at(new_tips, index) + Enum.at(bills, index)]
recursiveFn.(index + 1, new_tips, new_totals, recursiveFn)
false -> [tips, totals]
end
end
IO.puts(
calcTipsAndTotals.(0, [], [], calcTipsAndTotals)
)
If you pass a list to IO.puts
, it expects the argument to be valid IO data, but the result of your function is not, it's a list of lists of floats.
The simplest fix is to use IO.inspect
instead:
calcTipsAndTotals.(0, [], [], calcTipsAndTotals) |> IO.inspect()
Simplified example:
iex(1)> IO.puts([[1.0]])
** (ArgumentError) errors were found at the given arguments:
* 2nd argument: not valid character data (an iodata term)
(stdlib 4.2) io.erl:99: :io.put_chars(:standard_io, [[[1.0]], 10])
iex:1: (file)
iex(1)> IO.inspect([[1.0]])
[[1.0]]
[[1.0]]