2017-10-20 24 views
0

我想停止reduce_while當我的函數來獲取{:錯誤,原因},而不是虛假停止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!!!!!"} 

回答

2

如果要與來自功能的響應匹配,請使用case

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