测试Elixir中的十进制数据类型?

Emi*_*ily 1 elixir

Elixir Decimal包中是否有等效的is_string,is_number,is_integer,is_binary?

如果没有,为Decimal进行模式匹配的方法是什么?

Ste*_*len 5

Decimal是一个Elixir结构.因此,您可以使用%Decimal {}进行匹配.这可以添加到您的函数子句或case语句中.以下是几个例子:

def add(%Decimal{} = x, %Decimal{} = y), do: Decimal.add(x, y)

case num do
  %Decimal{} = x -> # ...
  num when is_integer(num) -> # ...
  _ -> # default case
end
Run Code Online (Sandbox Code Playgroud)

相同的方法适用于匹配任何Elixir结构.匹配规则类似于maps.但是,结构只包含它们定义的字段,并且所有这些字段都存在于结构中.

这意味着您无法匹配存在的文件必须在默认值上完成.例如:

# to match a struct that contains the `:mode` key you can do this:

def my_fun(%{mode: _}), do: # matches if the :mode key is present
def my_fun(%{}), do: # default case when map does not contain the :mode key

# to do the same with a struct

def MyStruct do
  defstruct mode: nil, other: true
end

def my_fun(%MyStruct{mode: mode}) when not is_nil(mode), do: # do something with mode
def my_fun(%MyStruct{}), do: # default case when mode is nil
Run Code Online (Sandbox Code Playgroud)