在 Elixir 世界的循环中间 return 的替代方法是什么

What is the alternative way to return in the middle of loop in the Elixir world

我对 Elixir 还是个新手。我正在尝试创建一个接受请求列表并处理每个请求的方法。 Return {:ok, "success"} 如果全部通过或 {:error, error_reason} 如果一个失败。

在其他语言中,我可以做这样的事情。假设过程函数 return {:ok, "success"} 或 {:error, error_reason}.

def func(requests):
   for request in requests:
       if {:error, error_reason} <- process(request):
           return {:error, error_reason}

   return {:ok, "success"}
end

在 Elixir 世界中执行此操作的正确方法是什么?

我会使用递归:

def func([head | tail]) do
  case process(head) do
    {:error, reason} -> {:error, reason}
    {:ok, _} -> func(tail)
  end
end

def func([]), do: {:ok, "success"}

循环本质上是命令式的,而 Elixir 本质上是一种函数式语言,因此我认为递归和 higher-order 函数是使用循环的更自然的替代方法。