lix剂中的多个条件修改变量

dri*_*nor -1 elixir

如何用Elixir编写此Ruby代码?

value = 0
value += 3 if cond1
value += 2 if cond2
value += 8 if cond3
value -= 3 if cond4
Run Code Online (Sandbox Code Playgroud)

Bre*_*tty 5

如果要使用管道,可以创建一个辅助函数。

def add_if(total, condition, value) do
  if condition, do: total + value, else: total
end


value =
  0
  |> add_if(cond1, 3)
  |> add_if(cond2, 2)
  |> add_if(cond3, 8)
  |> add_if(cond4, -3)
Run Code Online (Sandbox Code Playgroud)

根据您正在执行的操作,在修改数据的任何函数中都具有条件​​/逻辑也很有意义。因此,您的管道可能如下所示:

0
|> maybe_add_three("little pigs")
|> increment_by_two()
|> sum_with([4, 3, 1])
|> go_back_three_spaces(true)
Run Code Online (Sandbox Code Playgroud)