DEV Community

Cover image for Arity Of a Function
Diego Novais
Diego Novais

Posted on • Edited on

Arity Of a Function

Hey, Devs!

Do you know what an arity of a function is?

In math, the arity of a function represents the number of arguments of a function.

On programming is not different, an arity is also the representation of the number of its positional params.

When we have a function:

  • With No arguments, we say it has the arity 0 and can be called a Nullary function.

  • With only 1 argument, we say it has the arity 1 and can be called a Unary Function.

  • With 2 arguments, we say it has the arity 2 and can be called a Binary function.

  • With 3 arguments, we say it has the arity 3 and can be called a Ternary function.

  • With more than 3 arguments, now we can be called according to the quantity of the arguments post-fixed with ary.
    Eg.: 4-ary, 5-ary, 6-ary.

Let's code with Elixir...

defmodule Example do def say(), do: "Hey I am here!" def say(name), do: "Hey #{name}, I am here!" def say(first_name, last_name), do: "Hey #{first_name} #{last_name}, I am here!" end 
Enter fullscreen mode Exit fullscreen mode

The arity can be represented like that: function/number of arity

Eg.: When we executed the function Example.say/0

Example.say() --> "Hey I am here!" # Arity: say/0 # ------------------- 
Enter fullscreen mode Exit fullscreen mode

Eg.: When we executed the function Example.say/1

Example.say("Diego") --> "Hey Diego, I am here!" # Arity: say/1 # ------------------- 
Enter fullscreen mode Exit fullscreen mode

Eg.: When we executed the function Example.say/2

Example.say("Diego", "Novais") --> "Hey Diego Novais, I am here!" # Arity: say/2 
Enter fullscreen mode Exit fullscreen mode

I hope that makes sense to you! And see you in the next content.

Contacts
Email: contato@diegonovais.com.br
Linkedin: https://www.linkedin.com/in/diegonovais/
Twitter: https://twitter.com/diegonovaistech

Top comments (0)