How do you check for the type of variable in Elixir

前端 未结 8 1278
走了就别回头了
走了就别回头了 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:00

    I'll just leave this here for the sake of somebody hopefully figuring out an actually sane version. At the moment there are no good answers to this coming up on google...

    defmodule Util do
        def typeof(self) do
            cond do
                is_float(self)    -> "float"
                is_number(self)   -> "number"
                is_atom(self)     -> "atom"
                is_boolean(self)  -> "boolean"
                is_binary(self)   -> "binary"
                is_function(self) -> "function"
                is_list(self)     -> "list"
                is_tuple(self)    -> "tuple"
                true              -> "idunno"
            end    
        end
    end
    

    For the sake of completeness, test cases:

    cases = [
        1.337, 
        1337, 
        :'1337', 
        true, 
        <<1, 3, 3, 7>>, 
        (fn(x) -> x end), 
        {1, 3, 3, 7}
    ]
    
    Enum.each cases, fn(case) -> 
        IO.puts (inspect case) <> " is a " <> (Util.typeof case)
    end
    

    Here's a solution with protocols; I am not sure if they are faster(I sure hope they are not doing a loop over all types), but it is pretty ugly(and fragile; if they add or remove a basic type or rename, it will break it).

    defprotocol Typeable, do: def typeof(self)
    defimpl Typeable, for: Atom, do: def typeof(_), do: "Atom"
    defimpl Typeable, for: BitString, do: def typeof(_), do: "BitString"
    defimpl Typeable, for: Float, do: def typeof(_), do: "Float"
    defimpl Typeable, for: Function, do: def typeof(_), do: "Function"
    defimpl Typeable, for: Integer, do: def typeof(_), do: "Integer"
    defimpl Typeable, for: List, do: def typeof(_), do: "List"
    defimpl Typeable, for: Map, do: def typeof(_), do: "Map"
    defimpl Typeable, for: PID, do: def typeof(_), do: "PID"
    defimpl Typeable, for: Port, do: def typeof(_), do: "Port"
    defimpl Typeable, for: Reference, do: def typeof(_), do: "Reference"
    defimpl Typeable, for: Tuple, do: def typeof(_), do: "Tuple"
    
    IO.puts Typeable.typeof "Hi"
    IO.puts Typeable.typeof :ok
    

提交回复
热议问题