英文:
function gives "2nd argument: not valid character data" error
问题
我是新来的elixir,我正在尝试创建一个递归匿名函数,但由于某种原因,我的匿名函数在单独使用时按预期工作,但抛出了"2nd argument: not valid character data (an iodata term)"错误。
以下是代码:
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)
)
英文:
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)
)
答案1
得分: 2
<!-- language-all: lang-elixir -->
如果你将一个列表传递给 `IO.puts`,它期望参数是有效的 [IO 数据](https://hexdocs.pm/elixir/IO.html#module-io-data),但你的函数的结果不是,它是一个包含浮点数列表的列表。
最简单的解决方法是使用 [`IO.inspect`](https://hexdocs.pm/elixir/Kernel.html#inspect/2):
calcTipsAndTotals.(0, [], [], calcTipsAndTotals) |> IO.inspect()
---
简化的例子:
iex(1)> IO.puts([[1.0]])
** (ArgumentError) 在给定的参数中找到了错误:
* 第二个参数:不是有效的字符数据(一个 iodata 术语)
(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]]
英文:
<!-- language-all: lang-elixir -->
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]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论