Reputation: 831
Simple elixir program to separate out odd and even numbers and then printing those.
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
Note in error it shows only one part of map, i.e
{"even", [8, 6, 4, 2]}
File: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
Upvotes: 1
Views: 1406
Reputation: 84140
You are passing 2 arguments to the anonymous function you pass to Enum.map/2 - the function should have an arity of 1.
Try this:
Enum.map number_map, fn({k, v}) ->
{"even", [8, 6, 4, 2]}
is a tuple of 2 elements.
Upvotes: 3