Elixir / Phoenix Trying功能多次,赶上:好的

时间:2017-10-15 05:56:40

标签: elixir phoenix-framework

我有一个ping()函数,可以生成{:ok}{:error}

除非其中一个test()ping()回复,否则是否可以在返回错误之前制作包裹函数ping(),尝试{:ok} 5次?

如果test()在第一次尝试时可以从{:ok}返回ping(),那么它应该退出递归,但如果没有,则继续尝试ping()另外4次。

我已经检查了try/catch,但似乎无法确定如何使其发挥作用。任何提示赞赏!

1 个答案:

答案 0 :(得分:3)

这里不需要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}