Elixir 的 Kernel.SpecialForms.case/2: multi clauses "head" to execute the same "body"

Elixir's Kernel.SpecialForms.case/2: multi clauses "head" to execute the same "body"

我有一个关于 Elixir 中的 case 语句的简单问题(Kernel.SpecialForms.case/2 准确地说:GitHub, The awesome pretty doc)。有时,我想要多个 clauses/pattern 匹配来执行同一件事。我总是找到 guards 的解决方案来伪造它,但我想知道是否可以定义多个模式匹配来执行相同的代码块。

例如

在Ruby中(我没有在Ruby中使用case,这只是一个例子),你显然可以这样做:

case condition
  when clause1, clause2
    value1
  when clause3
    value3
end

在 Elixir 中,要避免这样的事情:

case [a, b] do
 [_, 0] -> a + b
 [_, 1] -> a + b
 [_, 2] -> a + b
 [_, _] -> 10 * b + a
end

我可能会做这样的事情(顺便说一句,这很好):

case [a, b] do
 [_, b] when b >= 0 and b <= 2 -> a + b
 [_, _] -> 10 * b + a
end

我想问的是有没有办法:

case condition
  clause1, clause2 -> puts "do something"
  clause3 -> puts "do something else"
end

感谢您的帮助。

不行,没办法。 :) 您可以将共享代码移动到一个函数中,然后从每个子句主体调用它。

举个例子说明@Jose 所说的:

defmodule Sharedcalls do
    def is_one(a=1,b), do: a_and_b_func
    def is_one(a, b=1), do: a_and_b_func
    def is_one(a, b), do: some_other_func
    defp a_and_b_func, do: IO.puts("a_and_b_func")
    defp some_other_func, do: IO.puts("Neither input is one")
end

Sharedcalls.is_one(1,0)
Sharedcalls.is_one(0,1)
Sharedcalls.is_one(0,0)

以防万一有人不清楚他在回答中的意思。我意识到这与您上面的示例并不完全平行,但我认为这足以让某人弄清楚。