Anonymous functions with multiple body

The point is that to me is like i’m using a switch statement, or a sort of case statement, and if the value that i pass match a case, i print the string, so what’s the difference to use a function like this or
use a switch in other languages?

Function clauses perform the control flow of switch statements (i.e. they allow branching on conditions) but they also bind values to variables at the same time. e.g. In the second line of:

handle_result = fn
  {:ok, result} -> IO.puts "handling the result..."
  {:error} -> IO.puts "an error is occurred"
end

a condition is checked (is the argument of the form {:ok, result}?), AND, if the condition is true, a value is bound to the variable ‘result’. A switch case does not assign values to variables but pattern matching does.

how can i use multiple bodies to compare if two values are equal or not equal with operators

You can use ‘when’ to add conditions to clauses:

fn 
  a,b when a > b -> ...
  a,b when a < b -> ...
  a,b -> 
end

last thing that i don’t get is, the argument of the function is implicit?

Not exactly. The arguments are pattern matched with each function clause. So for your example

fn a,b -> #  This is equivalent to fn a = arg1, b = arg2 ->
  a == b
end
7 Likes