Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does if(not nil) give me an ArgumentError?

defmodule My do
  def go do
    x = nil

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

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

According to Programming Elixir >= 1.6, p.35:

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

It doesn't seem to be true:

defmodule My do
  def go do
    x = false

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

In 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)> 
like image 809
7stud Avatar asked Dec 07 '25 18:12

7stud


1 Answers

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

Elixir 's latest definition of not function shows that it only receive false and true.

However, nil is not belongs to them, so it shows argument error.

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

nil is just an atom, that is nil === :nil.

You can consider using ! operator, which in fact is Kernel.! macro.

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

!nil will return true.

like image 145
chris Avatar answered Dec 09 '25 19:12

chris