Phoenix Framework : Enum.map while using with statement. Is it possible?

I want to get a result from the function using with statement. But what I want is exactly this;

For each row, I have to validate the role column and proceed, if a column is invalid I want the function to exit from with statement and give an output as :error.

The code below not working but is it possible to do something similar like this?

def get_validation_result(rows) do

    with {:ok, "valid"} <- rows
    |> Enum.map(fn row ->
      role = get_role(row)
      validate_role(role)
    end) do
      {:ok, "valid"}
    else
      {:error, error} ->
      IO.puts :stdio, "invalid"
    end

end

Solution 1:

What you need is Enum.reduce_while/3 which can traverse the enumerable and stop at a certain point.

On the other hand, with can group pattern matching when you're writing the code but has no dynamic ability.

def validate(rows) do
  Enum.reduce_while(rows, :ok, fn row, _ ->
    case get_role(row) |> validate_role() do
      :ok -> {:cont, :ok}
      other -> {:halt, other}
    end
  end)
end