ここにtry
/catch
の必要はありません。応答を一致させるcase
文を使用して、単純な再帰関数で十分です:
defmodule A do
# A function that returns `{:ok}` a third of the times it's called.
def ping, do: if :random.uniform(3) == 1, do: {:ok}, else: {:error}
# 5 attempts.
def test(), do: test(5)
# If 1 attempt is left, just return whatever `ping` returns.
def test(1), do: ping()
# If more than one attempts are left.
def test(n) do
# Print remaining attempts for debugging.
IO.inspect {n}
# Call `ping`.
case ping() do
# Return {:ok} if it succeeded.
{:ok} -> {:ok}
# Otherwise recurse with 1 less attempt remaining.
{:error} -> test(n - 1)
end
end
end
テスト:
iex(1)> A.test
{5}
{4}
{3}
{2}
{:ok}
iex(2)> A.test
{5}
{4}
{3}
{2}
{:error}
iex(3)> A.test
{5}
{:ok}
iex(4)> A.test
{5}
{:ok}
iex(5)> A.test
{5}
{4}
{:ok}
あなたの答えをありがとう!まさに私が探していたもの。良い一日を! – Ilya