Probably a very basic Elixir question,
I want to sum the even number from a 1 to 10 and output it to IO.puts
First I try doing it this way:
1..10
|> Enum.filter(fn (x) -> rem(x, 2) == 0 end)
|> Enum.sum
|> IO.puts
Which works as expected.
Then I try defining that function inside a module as such:
defmodule Test do
def is_even(x) do
rem(x, 2) == 0
end
end
1..10
|> Enum.filter(Test.is_even)
|> Enum.sum
|> IO.puts
But this gives me the following error on compilation:
** (UndefinedFunctionError) undefined function: Test.is_even/0
Test.is_even()
tmp/src.exs:8: (file)
(elixir) src/elixir_lexical.erl:17: :elixir_lexical.run/3
(elixir) lib/code.ex:316: Code.require_file/2
Why is it looking for is_even/0 when it should( in my intention) be looking for is_even/1?
I don't understand why this is, especially since doing this:
defmodule Test do
def hello(x) do
IO.puts(x)
end
end
Test.hello("Hello World!")
Works completely fine.
I also just found out this works:
defmodule Test do
def is_even() do
fn (x) -> rem(x, 2) == 0 end
end
end
1..10
|> Enum.filter(Test.is_even)
|> Enum.sum
|> IO.puts
Why is it using the return of the function to use as a function instead of using the function itself?
Is there a way to make this work without having to return anonymous functions inside functions?