【问题标题】:conditional guard clauses in elixir长生不老药中的条件保护子句
【发布时间】:2017-06-08 21:28:11
【问题描述】:

有没有办法在函数保护子句中使用orand表达式:

defmodule Test do
   def testfn(arg1, arg2) when is_nil(arg1) || is_nil(arg2), do: :nothing

   def testfn2(arg1, arg2) when is_nil(arg1) && is_nil(arg2), do: :nothing
end

【问题讨论】:

    标签: elixir


    【解决方案1】:

    Guard 表达式不支持 &&||(在 LHS 上接受任何值),但仅支持 andor(在 LHS 上只接受布尔值)。由于is_nil总是返回一个布尔值,你可以切换到使用andor

    defmodule Test do
       def testfn(arg1, arg2) when is_nil(arg1) or is_nil(arg2), do: :nothing
    
       def testfn2(arg1, arg2) when is_nil(arg1) and is_nil(arg2), do: :nothing
    end
    

    https://hexdocs.pm/elixir/master/guards.html 包含守卫中允许的所有函数/运算符的列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      相关资源
      最近更新 更多