使用Elixir的“ with”有什么好处

时间:2020-07-02 17:06:58

标签: elixir

I saw this code at the Elixir School

with {:ok, user} <- Repo.insert(changeset),
     {:ok, token, full_claims} <- Guardian.encode_and_sign(user, :token, claims) do
  important_stuff(token, full_claims)
end

我并没有简单的区别:

{:ok, user} <- Repo.insert(changeset),
{:ok, token, full_claims} <- Guardian.encode_and_sign(user, :token, claims)
important_stuff(token, full_claims)

1 个答案:

答案 0 :(得分:3)

没有{:ok, user} <- Repo.insert(changeset)

with首先会提高(CompileError) undefined function <-/2。您可能是说{:ok, user} = Repo.insert(changeset)

Kernel.SpecialForms.with/1在某种程度上扮演了 monad 的角色。

如果 RHO LHO 匹配,则转到下一个子句。否则,它将立即提早返回不匹配的 RHO ,并丢弃所有其他子句。如果前一个成功,则考虑并应考虑应依次应用的几个功能。遵循这些原则。

with {:ok, text} <- File.read(name),
     {:ok, words} <- MyStemmer.get_words(text),
     count when in_integer(count) <- Enum.count(words),
  do: IO.puts("File contained #{count}" words)

如果没有这样的文件,则整个代码段将返回{:error, :enoent},因为第一个子句将无法对 LHO 进行模式匹配。

{:ok, text} = File.read(name)会在没有这样的文件时引发MatchError


三年前,我已经写了一个blog post主题,也许仍然值得一读。

相关问题