1

I have maybe a stupid question. Coming from a Ruby background, if I forgot a few required arguments to a method, the interpreter will throw a missing argument error, and I would know that it was a small quick mistake.

As I'm still new to Elixir, I would get undefined function Random.some_function/2 when maybe Random.some_function/3 was defined but I just happened to forgot.

Other than googling or looking at the documentation, is there a quicker way to find out? Just curious.

owyongsk
  • 2,349
  • 1
  • 19
  • 21

2 Answers2

2

Unlike Elixir, Ruby does not support Method overloading, and maintains only one method in the method look up chain with a unique name. Hence, it can point you to error related to missing parameters.

Below is a Ruby example, which shows that moment we define another function with same name, we lose the previous definition of that function.

def test(param)
    p param
end

test() #=> wrong number of arguments (0 for 1) (ArgumentError)

def test(param_1, param_2)
    p param_1, param_2
end

test("A") #=> wrong number of arguments (1 for 2) (ArgumentError)

On the contrary, in Elixir, a function is uniquely identified by its containing module, its name, and its arity. Two functions with the same name but different arities are two different functions. Below is one example:

defmodule Rectangle do
  def area(a), do: area(a, a)
  def area(a, b), do: a * b
end

IO.inspect Rectangle.area(2)      
#=> 4

IO.inspect Rectangle.area(2, 4)   
#=> 8

IO.inspect Rectangle.area()       
#=> ** (UndefinedFunctionError) undefined function: Rectangle.area/0

Now, if you try to invoke Rectangle.area without any parameters, Elixir can only complain that the function with 0 arity does not exist, but it cannot possibly figure out that which of the two Rectangle.area method you intended to invoke. May be an Elixir IDE (in future) can help with this kind of situation, but at present, it seems one has to look up the documentation/code to figure out the correct arity of a function.

Community
  • 1
  • 1
Wand Maker
  • 18,476
  • 8
  • 53
  • 87
0

In the iex terminal you can use h keyword that will show you the documentation of the required function. This will work all functions that have defined a doc or document in the syntax. Example

h Enum.reduce

coderVishal
  • 8,369
  • 3
  • 35
  • 56