Question

Why does Elixir have guard clauses for function definition in the module and not in function itself? I find the following to be more intuitive:

def fibonnaci(n) do
  when n == 0, do: 0
  when n == 1, do: 1
  when n > 1 do
    fibonnaci(n - 2) + fibonnaci(n - 1)
  end
end
Was it helpful?

Solution

I am not sure if this is a question about how to write that code or about why the language was designed like that. Assuming it is the first, you have:

def fibonnaci(0), do: 0
def fibonnaci(1), do: 1
def fibonnaci(n), do: fibonnaci(n - 2) + fibonnaci(n - 1)

In case you want everything in the same function body, you could use a case:

def fibonnaci(n) do
  case n do
    0 -> ...

If you meant the latter, the answer may become clearer once you get more familiar with the language because the proposed example is not valid syntax (Elixir relies on a simple syntax with very few keywords where everything abides to the same rules).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top