2
votes

Trying to pass a custom function to the following function but I have no luck.

   defmodule M do
     def custom_fn([head|tail],fnce) do
        fnce.(head)
        custom_fn(tail,fnce)
      end

     def custom_fn([]), do: nil

   end

Trying to call it like this:

M.custom_fn([1,2,3], (fn(x) -> x * 10 end))

Getting this

** (FunctionClauseError) no function clause matching in M.custom_fn/2    

The following arguments were given to M.custom_fn/2:

    # 1
    []

    # 2
    #Function<6.99386804/1 in :erl_eval.expr/5>

test.ex:11: M.custom_fn/2

Also, what does the following message say? M.custom_fn/2
To be more specific, I don't understand /2.

3

3 Answers

2
votes

You forgot to add the second argument to the base case. Like the error says, now you don't have any clause that matches ([], <function>).

def custom_fn([]), do: nil

should be

def custom_fn([], _), do: nil
2
votes

/2 is a function arity.

The issue is not with a function at all.

def custom_fn([head|tail],fnce) do
  fnce.(head)
  # ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓ HERE
  custom_fn(tail,fnce)
end

The last call on an empty array is not matched. You should update the second clause to accept the second argument:

def custom_fn([], _), do: nil
2
votes

As other answers gives the explanation, I will give the right version.

defmodule M do
  def custom_fn([], _), do: nil
  def custom_fn([head|tail],fnce) do
    fnce.(head)
    custom_fn(tail,fnce)
  end
end

IO.inspect M.custom_fn([1,2,3], (fn(x) -> x * 10 end))