Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Invalid expression in guard, case is not allowed in guards" error

The following code is deemed an error by mix:

case test do
      ...
      t when !is_list(t) -> false
      ...
end

The error is "Invalid expression in guard, case is not allowed in guards".

However, if I remove the !, i.e. write

case test do
      ...
      t when is_list(t) -> false
      ...
end

no error is reported.

This can't be right? ! should just be the negation function.

like image 620
xji Avatar asked Oct 17 '25 07:10

xji


2 Answers

I think it works if you use the keyword not instead of !.

Not is allowed in guard tests, ! is not allowed in guard tests.

like image 159
zwippie Avatar answered Oct 21 '25 02:10

zwippie


! is not a negation function, it is a macro.

See the code in elixir, lib/elixir/lib/kernel.ex: 1552,

 defmacro !value

  defmacro !{:!, _, [value]} do
    optimize_boolean(
      quote do
        case unquote(value) do
          x when :"Elixir.Kernel".in(x, [false, nil]) -> false
          _ -> true
        end
      end
    )
  end

  defmacro !value do
    optimize_boolean(
      quote do
        case unquote(value) do
          x when :"Elixir.Kernel".in(x, [false, nil]) -> true
          _ -> false
        end
      end
    )
  end

The ! macro expanded is a case statement, which is not allowed in elixir guards.

And not is a erlang function:

  @spec not true :: false
  @spec not false :: true
  def not value do
    :erlang.not(value)
  end
like image 30
chris Avatar answered Oct 21 '25 01:10

chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!