用元组停止reduce_while

时间:2017-10-20 09:43:41

标签: elixir

当我的函数得到{:error,reason}而不是false

时,我想停止reduce_while

我的代码是:

Enum.reduce_while(
      [1,2,3,4],
      0,
      fn filename, _foo ->
        if carica() do
          IO.puts "OK"
          {:cont, carica()}
        else
          IO.puts "KO"
          {:halt, carica()}
        end
      end
    )

  def carica() do
    {:error,"ERROR!!!!!"}
  end

我想要输出

"KO"
{:error,"ERROR"}

因为这样我有

OK
OK
OK
OK
{:error, "ERROR!!!!!"}

1 个答案:

答案 0 :(得分:2)

如果要模拟匹配函数的响应,请使用case

case response = carica() do
  {:error, reason} ->
    IO.puts "KO"
    {:halt, response}
  _ ->
    IO.puts "OK"
    {:cont, response}
end