2

I'm getting what I consider to be a rather strange warning when trying to compile an Elixir module (using Elixir 1.3.2 and Erlang R19). The code is from the book Introducing Elixir:

defmodule Drop do
    def fall_velocity(distance) do
        :math.sqrt(2 * 9.8 * distance)
    end

    def fall_velocity(distance, gravity \\ 9.8) do
        :math.sqrt(2 * gravity * distance)
    end
end

When I compile it, the shell says:

warning: this clause cannot match because a previous clause at line 2 always matches
  drop.ex:6

Line 6 is the second function definition, and line 2 is the first one.

However, when I use the code, it works fine:

iex(12)> Drop.fall_velocity(20)     
19.79898987322333
iex(13)> Drop.fall_velocity(20, 1.6)
8.0

What, then, is the meaning of that warning?

1 Answer 1

3

The problem is that def fall_velocity(distance, gravity \\ 9.8) do will define 2 functions, one with arity 1, that just falls the arity 2 version with gravity set to 9.8, and one with arity 2. In this case, you don't need the first clause at all. The second one will set the gravity to 9.8 by default and you'll get the same answer as arity 1.

defmodule Drop do
  def fall_velocity(distance, gravity \\ 9.8) do
    :math.sqrt(2 * gravity * distance)
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

Hey, thanks again for answering! So, in my code, the second function was kind of shadowing the first one? If not, why did the shell say that line 2 will always be matched?
Oh, perhaps the warning was because the new function generated two clauses, the first one being shadowed by the function defined before. That might explain it ...
Yes, the second one generated a 1 arity function which could never match because of the first function you defined.

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.