How do you check for the type of variable in Elixir

前端 未结 8 1274
走了就别回头了
走了就别回头了 2021-01-30 15:25

In Elixir how do you check for type such as in Python:

>>> a = \"test\"
>>> type(a)

>>> b =10
>>> type(b         


        
相关标签:
8条回答
  • 2021-01-30 16:05

    Another approach is to use pattern matching. Say you're using Timex, which uses a %DateTime{} struct, and you want to see if an element is one. You can find a match using pattern matching in the method.

    def is_a_datetime?(%DateTime{}) do
      true
    end
    
    def is_a_datetime?(_) do
      false
    end
    
    0 讨论(0)
  • 2021-01-30 16:06

    I came across a situation need to check the parameter need to be certain type. Maybe can active a better way.

    Like this:

    @required [{"body", "binary"},{"fee", "integer"}, ...]
    defp match_desire?({value, type}) do
      apply(Kernel, :"is_#{type}", [value])
    end
    

    Usage:

    Enum.map(@required, &(match_desire?/1))
    
    0 讨论(0)
提交回复
热议问题