2015-11-18 133 views
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 

回答

3

你是路過2個參數傳遞給匿名函數Enum.map/2 - 功能應該有1的秩序。

試試這個:

Enum.map number_map, fn({k, v}) -> 

{"even", [8, 6, 4, 2]}是一個2元素的元組。

相關問題