Using Elixir Shorthand with Anonymous Multiple Body Features

Given the Elixir function add1 = fn a -> a + 1 end, I know that it can be expressed in abbreviated notation asadd1 = &(&1 + 1)

Is there a way to use shorthand notation with multi-body functions? For example, the following function returns a larger number of two numbers.

max = fn
  a, b when a > b -> a
  _a, b -> b
end

Is it possible to express this anonymous function using the Elixir abbreviation?

+4
source share
2 answers
max = &
  case &1 > &2 do
    true -> &1
    false -> &2
  end

I would not consider this as an abbreviated form.

The general solution will contain all the arguments in case:

max = &
  case {&1, &2} do
    {a, b} when a > b -> a
    {a, b} -> b
  end

But this will only increase the time.

+1
source

This example works

max = fn
    (a, b) when a >= b -> a
    (_a, b) -> b
end

IO.puts max.(0, 2) # 2
IO.puts max.(2, -5) # 2
0
source

Source: https://habr.com/ru/post/1659134/


All Articles