Canonical way to deconstruct function parameters

What’s the canonical way to deconstruct a function parameter? For example:

def f(x) do
  case x do
    {x1,x2} -> #dosomething

How can I rewrite that without the case statement? I want to deconstruct the parameter x and the only reason I have the case statement there is because it lets me create a match clause afterwards. I think I can write something like

 def f({x1, x2}) do

but what are the other ways?

1 Like

I’m not sure what you mean by “it lets me create a match clause afterward”.

In the event where you’re just immediately calling case on the function parameters, I would almost always simply match on the function head itself. You can use multiple clauses to handle multiple patterns, IE

def foo({x1, x2}), do: x1 + x2
def foo(other), do: other

If you need access to both the destructured data and the whole data you could have a match which looks like this:

def f({x1, x2} = x) do ...

Now you can use x1, x2 and x in your code


In Dave Thomas’ Programming Elixir book, a sample solution for FizzBuzz looks like this:

fizzbuzz = fn
  0, 0, _ -> "FizzBuzz"
  0, _, _ -> "Fizz"
  _, 0, _ -> "Buzz"
  _, _, c -> c
1 Like