Elixir Function Headers

While playing with the new exercise.io problem, the prime factorization of a number, I came across an interesting feature in Elixir.

I tried defining a couple of incarnations of pattern matched function with default values, like this:

defp decompose(1, divisor \\ 2, acc \\ []) do
  ...
end

defp decompose(number, divisor \\ 2, acc \\ []) do
  ...
end

But, that did not do well with Elixir compiler. It seems you need to add an empty clause, sort of a function header, as explained in this Github issue:

# function header / empty clause
defp decompose(number, divisor \\ 2, acc \\ [])

defp decompose(1, divisor, acc) do
  ...
end

defp decompose(number, divisor, acc) do
  ...
end

And then, only that empty clause requires default values. Nice to know!

Advertisements
Tagged , ,

2 thoughts on “Elixir Function Headers

  1. Nice tip! Thanks for sharing 🙂
    BTW shouldn’t be the last function like this?

    “`
    defp decompose(number, divisor, acc)

    end
    “`

    Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: