2

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 Answers 3

2

/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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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))

3 Comments

And make sure the function heads are in the order in which YongHao gives them. Order is important on that particular construct.
@OnorioCatenacci no, in this particular case the order in not important. [] and [h|t] are never matched simultaneously. Otherwise OP would experience infinite recursion instead of match error.
Thanks for the correction; I'm just accustomed to order of function heads being important in general so I assumed it'd matter here too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.