What are the differences between Clause, Function and Module?

All seems like the same

A module is a container that contains one or many function. A clause is a branch in a case expression or multiheaded function.

But if you really feel they are the same, could you please point us to the resource that makes you do so? Perhaps we can clarify things a bit for you?

4 Likes

hello.exs:

defmodule Calc do
  def go(:show, x) do    # go/2 clause 1
    IO.puts x
  end
  def go(:double, x) do  # go/2 clause 2
    IO.puts 2*x
  end

  def go(x, y, z) do     # go/3
    IO.puts x+y+z
  end
end

defmodule Auto do
  def go(:fast, x) do    # go/2 in another module (=namespace)
    IO.puts "Going #{10 * x} mph!"
  end
end


Auto.go(:fast, 10)
Calc.go(:show, 20)
Calc.go(:double, 20)

Running the code:

~/elixir_programs$ elixir hello.exs
Going 100 mph!
20
40

module: Groups functions under a common name (also known as a namespace) to prevent name clashes with other functions.

function: Takes some input in the form of arguments and performs some task.

clause: Functions can have multiple clauses and elixir pattern matches the function arguments to determine which clause executes. In most languages that people studied before learning elixir, defining multiple function clauses would cause an error.

3 Likes

I’m cleared thanks

2 Likes