概要
paiza.ioでelixirやってみた。
型が分からないので、調べてみた。
サンプルコード
defmodule TypeBy do
@spec get(any) :: String.t()
def get(x) do
dict = %{
&is_atom/1 => "Atom",
&is_binary/1 => "Binary",
&is_bitstring/1 => "BitString",
&is_boolean/1 => "Boolean",
&is_float/1 => "Float",
&is_function/1 => "Function",
&is_integer/1 => "Integer",
&is_list/1 => "List",
&is_map/1 => "Map",
&is_number/1 => "Number",
&is_pid/1 => "Pid",
&is_reference/1 => "Reference",
&is_tuple/1 => "Tuple",
}
typename_list = Enum.filter_map(dict, fn {pred, _} ->
pred.(x)
end, fn {_, name} ->
name
end)
if Enum.empty?(typename_list) do
"unknown type"
else
Enum.join(typename_list, " & ")
end
end
end
x = "hello"
IO.puts "type: #{TypeBy.get(x)}"
x = 13
IO.puts "type: #{TypeBy.get(x)}"
x = 'hello'
IO.puts "type: #{TypeBy.get(x)}"
x = 3.14
IO.puts "type: #{TypeBy.get(x)}"
x = true
IO.puts "type: #{TypeBy.get(x)}"
x = :hoge
IO.puts "type: #{TypeBy.get(x)}"
x = {6}
IO.puts "type: #{TypeBy.get(x)}"
x = [7]
IO.puts "type: #{TypeBy.get(x)}"
実行結果
type: Binary & BitString
type: Integer & Number
type: List
type: Float & Number
type: Atom & Boolean
type: Atom
type: Tuple
type: List
成果物
以上。