Nair
Nair

Reputation: 7458

How would one run a functions with same name?

I am new Elixir and really enjoying it. I hit a wall when trying to use functions with same name. Here is an example

defmodule ChangeName do
  def convert(:captilize, name), do:  String.capitalize(name)
  def convert(:lower, name), do: String.downcase(name)
end

I am using iex and the basic calls where ChangeName.convert.captilize but how do I run these functions?

Thanks

Upvotes: 1

Views: 366

Answers (1)

Paweł Obrok
Paweł Obrok

Reputation: 23164

The example you give doesn't define two functions with the same name, but a single multiclause function. It is roughly equivalent to:

defmodule ChangeName do
  def convert(conversion, name) do
    case conversion do
      :capitalize -> String.capitalize(name)
      :lower -> String.downcase(name)
    end
  end
end

And is called accordingly:

ChangeName.convert(:capitalize, "john")
ChangeName.convert(:lower, "JOHN")

In fact in Erlang it's impossible to define two functions that have the same name and arity.

Upvotes: 6

Related Questions