#TIL #elixirlang is_atom(nil) 값은?

is_atom(nil)

값은 뭘까? is_atom/1 함수는 인자가 atom 일 때, true를 리턴하고 아니면 false를 리턴한다.

true

true가 나온다. nil은 atom이기 때문이다.

iex> is_atom(true)
true
iex> is_atom(false)
true

true와 false도 마찬가지다. nil, true, false 모두 atom이다.

iex> nil == :nil
true
iex> true == :true
true
iex> false == :false
true

Elixir allows you to skip the leading : for the atoms false, true and nil.

- Basic types

nil, true, false는 atom인데도 : 문자를 빼고 쓸 수 있게 편의 문법(syntactic sugar)으로 지원한다.

atom이기 때문에 guard를 쓸 때, 주의해야 한다.

def some_function(param) when is_atom(param), do: # do somthing

이런 함수를 만들면 param으로 nil과 true, false도 들어올 수 있다. 만약 이걸 의도하지 않았다면

def some_function(param) when is_atom(param) and
  not is_boolean(param) and
  not is_nil(param),
  do: # do somthing

이렇게 boolean과 nil을 guard로 거르게 한다던지

def some_function(param) when is_boolean(param) , do: # nothing
def some_function(param) when is_nil(param), do: # nothing
def some_function(param) when is_atom(param), do: # do somthing

먼저 nil과 boolean 일때 매칭해서 처리하도록 코드를 짜야 한다.

참고

Feedback plz <3 @ohyecloudy, ohyecloudy@gmail.com

A Random Post