gpt4 book ai didi

elixir - 在 Elixir 中测试十进制数据类型?

转载 作者:行者123 更新时间:2023-12-04 01:45:53 24 4
gpt4 key购买 nike

Elixir Decimal 包是否有 is_string、is_number、is_integer、is_binary 等价物?

如果不是,小数模式匹配的一些方法是什么?

最佳答案

Decimal 是一个 Elixir 结构。因此,您可以使用 %Decimal{} 对其进行匹配。这可以添加到您的函数子句或 in 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

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

这意味着您不能匹配必须在默认值上完成的文件的存在。例如:

# 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

关于elixir - 在 Elixir 中测试十进制数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43597114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com