Skip to content

Commit

Permalink
Describe how Elixir names functions. Addresses elixirschool#583. (eli…
Browse files Browse the repository at this point in the history
…xirschool#599)

* Describe how Elixir names functions. Addresses elixirschool#583.

* Accept rewording on arity from @ybur-yug
  • Loading branch information
scouten authored and doomspork committed Aug 29, 2016
1 parent 76746ce commit 9321df5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lessons/basics/collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ iex> [1, 2] ++ [3, 4, 1]
[1, 2, 3, 4, 1]
```

A side note about the name (`++/2`) format used above: In Elixir (and Erlang, upon which Elixir is built), a function or operator name has two components: the name you give it (here `++`) and its _arity_. Arity is a core part of speaking about Elixir (and Erlang) code. It is the number of arguments a given function takes (two in this case). Arity and the given name are combined with a slash. We'll talk more about this later; this knowledge will help you understand the notation for now.


### List Subtraction

Support for subtraction is provided via the `--/2` operator; it's safe to subtract a missing value:
Expand Down
23 changes: 23 additions & 0 deletions lessons/basics/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,29 @@ iex> Length.of [1, 2, 3]
3
```

### Function Naming and Arity

We mentioned earlier that functions are named by the combination of given name and arity (number of arguments). This means you can do things like this:

```elixir
defmodule Greeter2 do
def hello(), do: "Hello, anonymous person!" # hello/0
def hello(name), do: "Hello, " <> name # hello/1
def hello(name1, name2), do: "Hello, #{name1} and #{name2}"
# hello/2
end

iex> Greeter2.hello()
"Hello, anonymous person!"
iex> Greeter2.hello("Fred")
"Hello, Fred"
iex> Greeter2.hello("Fred", "Jane")
"Hello, Fred and Jane"
```

We've listed the function names in comments above. The first implementation takes no arguments, so it is known as `hello/0`; the second takes one argument so it is known as `hello/1`, and so on. Unlike function overloads in some other languages, these are thought of as _different_ functions from each other. (Pattern matching, described just a moment ago, applies only when multiple definitions are provided for function definitions with the _same_ number of arguments.)


### Private Functions

When we don't want other modules accessing a specific function we can make the function private. Private functions can only be called from within their own Module. We define them in Elixir with `defp`:
Expand Down

0 comments on commit 9321df5

Please sign in to comment.