Compiler warning: clauses for the same def should be grouped together

Hello,

I’m making my way through Programing Elixir and after I completed an exercise I got a compiler warning. I’m still new to the language and I don’t exactly know how to get rid of it.

Here’s my code:

defmodule Solution do
  def span(from, to) when from == to do
    [from]
  end
  def span(from, to) do
    [from] ++ span(from + 1, to)
  end

  def is_prime(n) when n <= 1 do
    false
  end
  def is_prime(n) when n <= 3 do
    true
  end
  def is_prime(n) when rem(n, 3) == 0 do
    false
  end
  def is_prime(n) when rem(n, 2) == 0 do
    false
  end
  defp is_prime(n, i) when i*i <= n do
    cond do
      rem(n, i) == 0 -> false
      rem(n, i+2) == 0 -> false
      true -> is_prime(n, i + 6)
    end
  end
  defp is_prime(_n, _i) do
    true
  end
  def is_prime(n) do
    is_prime(n, 5)
  end

  def get_primes(num) do
    for n <- Solution.span(2, num), Solution.is_prime(n), do: n
  end
end

# Exercise: ListsAndRecursion-7
# In the last exercise of Chapter 7, ​Lists and Recursion​, you wrote a span function.
# Use it and list comprehensions to return a list of the prime numbers from 2 to n.

IO.inspect Solution.get_primes(100)

Just move your last is_prime/1 up, where all it’s other defs are.

In Elixir/Erlang, functions are identified by name and arity, thus all your is_prime with same arity should be grouped together.

We could actually improve the warning here since we know when they have the same name but different arities. I will open up an issue. :slight_smile:

5 Likes

This is a single function composed of multiple clauses: Solution.is_prime/1

  def is_prime(n) when n <= 1 do
    false
  end
  def is_prime(n) when n <= 3 do
    true
  end
  def is_prime(n) when rem(n, 3) == 0 do
    false
  end
  def is_prime(n) when rem(n, 2) == 0 do
    false
  end
  def is_prime(n) do
    is_prime(n, 5)
  end

This is a separate single (private) function: Solution.is_prime/2

  defp is_prime(n, i) when i*i <= n do
    cond do
      rem(n, i) == 0 -> false
      rem(n, i+2) == 0 -> false
      true -> is_prime(n, i + 6)
    end
  end
  defp is_prime(_n, _i) do
    true
  end
1 Like