1
簡單的靈藥程序分離出奇數和偶數,然後打印這些。(BadArityError)爲什麼它的拋出錯誤?
iex(22)> c("testmap.ex")
testmap.ex:1: warning: redefining module TestModule
[TestModule]
iex(23)> TestModule.test_map_reduce
** (BadArityError) #Function<0.56012634/2 in TestModule.pretty_print/1> with arity 2 called with 1 argument ({"even", [8, 6, 4, 2]})
(elixir) lib/enum.ex:1047: anonymous fn/3 in Enum.map/2
(stdlib) lists.erl:1262: :lists.foldl/3
(elixir) lib/enum.ex:1047: Enum.map/2
錯誤提示,僅顯示一個地圖的一部分,即
{"even", [8, 6, 4, 2]}
文件:testmap.ex
defmodule TestModule do
def test_map_reduce do
list = [1,2,3,4,5,6,7,8,9]
map = Enum.reduce list, %{}, fn(n, acc) ->
key = getKey(n)
case acc[key] do
nil -> Map.put acc, key, [n]
list -> Map.put acc, key, [n|list]
end
end
pretty_print(map)
end
def getKey(n) do
case rem n, 2 do
0 -> "even"
_ -> "odd"
end
end
def pretty_print(number_map) do
Enum.map number_map, fn(k, v) ->
IO.inspect k
IO.inspect v
end
end
end