【问题标题】:Why does if(not nil) give me an ArgumentError?为什么 if(not nil) 会给我一个 ArgumentError?
【发布时间】:2018-12-03 10:55:10
【问题描述】:
defmodule My do
  def go do
    x = nil

    if(not x) do
      IO.puts "hello"
    else
      IO.puts "goodbye"
    end
  end
end

在 iex 中:

/elixir_programs$ iex c.exs
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)

iex(1)> My.go
** (ArgumentError) argument error
    c.exs:5: My.go/0

iex(1)> 

根据Programming Elixir >= 1.6,第35页:

Elixir 具有三个与布尔运算相关的特殊值:true、 假的,零。 nil 在布尔上下文中被视为 false。

这似乎不是真的:

defmodule My do
  def go do
    x = false

    if (not x) do
      IO.puts "hello"
    else
      IO.puts "goodbye"
    end
  end
end

在 iex 中:

~/elixir_programs$ iex c.exs
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)

iex(1)> My.go       
hello
:ok

iex(2)> 

【问题讨论】:

  • 您是否尝试过切换到 cond 并查看它是否可以编译?或者将语句切换到 if x do IO.puts "goodbye" else IO.puts "hello"

标签: if-statement null boolean elixir


【解决方案1】:
  @spec not true :: false
  @spec not false :: true
  def not value do
    :erlang.not(value)
  end

Elixir 对not 函数的最新定义显示它只接收falsetrue

但是nil不属于他们,所以显示argument error

Elixir 具有三个与布尔运算相关的特殊值:true、false 和 nil。 nil 在布尔上下文中被视为 false。

nil 只是一个atom,即nil === :nil

可以考虑使用!操作符,其实就是Kernel.!宏。

接收任何参数(不仅仅是布尔值)并返回true,如果 参数是falsenil;否则返回false

!nil 将返回 true

【讨论】:

    【解决方案2】:

    "Kernel.not/1" or not/1 需要一个布尔值

    注意:nilfalse 的其他值不同的是 true

    试试这个例子:

    x = nil
    if (x) do true else false end
    false
    

    短 if 条件和 true、false、nil 值的示例

    iex> if nil , do: true, else: false
    false
    iex> if !nil , do: true, else: false
    true
    iex> if false , do: true, else: false
    false
    iex> if !false , do: true, else: false
    true
    iex> if not false , do: true, else: false
    true
    iex> if true , do: true, else: false
    true
    iex> if !true , do: true, else: false
    false
    iex> if not true , do: true, else: false
    false
    

    【讨论】:

      猜你喜欢
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      相关资源
      最近更新 更多