gpt4 book ai didi

if-statement - 为什么 if(not nil) 给我一个 ArgumentError?

转载 作者:行者123 更新时间:2023-12-04 13:20:41 27 4
gpt4 key购买 nike

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 has three special values related to Boolean operations: true, false, and nil. nil is treated as false in Boolean contexts.

这似乎不是真的:

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)>

最佳答案

  @spec not true :: false
@spec not false :: true
def not value do
:erlang.not(value)
end

Elixir 对not 函数的最新定义表明它只接收falsetrue

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

Elixir has three special values related to Boolean operations: true, false, and nil. nil is treated as false in Boolean contexts.

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

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

Receives any argument (not just booleans) and returns true if the argument is false or nil; returns false otherwise.

!nil 将返回 true

关于if-statement - 为什么 if(not nil) 给我一个 ArgumentError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53592321/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com