Stephane Rolland
Stephane Rolland

Reputation: 39906

Using Enum.reduce, why that compiler "error undefined function my_func/0"

My code is below, and it's not clear for me why I have the compiler complaining:

rle.exs:3: warning: function reducer_fun/2 is unused
** (CompileError) rle.exs:15: undefined function reducer_fun/0
    (stdlib) lists.erl:1337: :lists.foreach/2
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6

Namely that supposes that Enum.reduce is expecting a reducer function of arity 0, which completely puzzles me.

Is there something obviously false in my code ? Why doesn't it use the defined reducer_fun ?

  defp reducer_fun(x,y) do y end

  @spec encode(String.t) :: String.t
  def encode(string) do
    cond do
      string == "" -> ""

      # the reduction is done here
      true -> Enum.concat(Enum.reduce(string, {:no_letter, 0, []}, reducer_fun))
    end

  end

Upvotes: 0

Views: 932

Answers (1)

Dogbert
Dogbert

Reputation: 222188

true -> Enum.concat(Enum.reduce(string, {:no_letter, 0, []}, reducer_fun))

should be

true -> Enum.concat(Enum.reduce(string, {:no_letter, 0, []}, &reducer_fun/2))

as Enum.reduce/3 expects a fn with arity 2 as the third argument, while your original code is trying to call a function in the same module named reducer_fun with no arguments (hence the error undefined function reducer_fun/0) and pass the returned value to Enum.reduce/3.

Edit: also, Strings aren't enumerable. You should pass the string to String.to_char_list, String.codepoints, or String.graphemes first to convert it into a list. The exact function to use depends on what you're trying to do.

Upvotes: 3

Related Questions