LoginSignup
12
1

Elixir &&とandの使い分けについて学ぶ

Last updated at Posted at 2023-12-21

このアンチパターンを読んでみました
https://hexdocs.pm/elixir/1.16.0-rc.0/code-anti-patterns.html#non-assertive-truthiness

う~~ん、そもそも&&とandの違いはなんですか?
試してみてみよう。

iex(6)> true and false 
false
iex(7)> true and nil  
nil
iex(8)> true and 2  
2
iex(9)> 1 and 2   
** (BadBooleanError) expected a boolean on left-side of "and", got: 1
    iex:9: (file)
iex(9)> nil and 2
** (BadBooleanError) expected a boolean on left-side of "and", got: nil
    iex:9: (file)
iex(9)> 1 && 1   
1
iex(10)> 1 && 2
2
iex(11)> 2 && 1
1
iex(12)> "a" && 1
1
iex(13)> nil && 1
nil
iex(14)> nil && IO.puts("hello")
nil
iex(15)> 1 && IO.puts("hello")  
hello
:ok
iex(16)> false and IO.puts("hello")
false
iex(17)> true and IO.puts("hello") 
hello
:ok
iex(18)> 

どちらも論理演算をするものらしい。
andの方は、andの左側の値はbool値でないとエラーになる。nilも不可。

if is_binary(name) && is_integer(age) do
  # ...
else
  # ...
end

このコードに問題はないんだけど、比較する値がbooleanだったら、and, or,notを使いましょう

if is_binary(name) and is_integer(age) do
  # ...
else
  # ...
end

使い分け方

演算子 引数の型
and, or,not boolean
&& || ! 任意の値。nil,falseを偽、それ以外を真
12
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
1