【问题标题】:Check if variable is of a custom type in Erlang?检查变量是否是 Erlang 中的自定义类型?
【发布时间】:2014-07-19 12:16:18
【问题描述】:

有没有办法在 Erlang 中检查变量是否属于自定义类型?

假设我在.hrl 文件中定义了一些记录和类型:

-record(custom_record, {
    attr1 :: list(),
    attr2 :: binary(),
    attr3 :: tuple()
}).

-record(another_record, {
    attr1 :: list(),
    attr2 :: binary(),
}).

-type custom_record() :: #custom_record{}.

-type another_record() :: #another_record{}.

-type custom_records() :: custom_record() | another_record().

有没有一种简单的方法可以检查我的 Erlang 代码中的记录是否为 custom_record?像这样的东西会很好:

is_custom_type(CustomRecord, custom_records). %=> true

我查看了文档,没有看到任何内置函数可以做到这一点。

【问题讨论】:

    标签: types erlang typechecking custom-type


    【解决方案1】:

    Erlang 标准库包含 is_record() BIF,它检查元组的第一个元素是否是适当的原子,请参阅 is_record/2,以便您可以像 is_record(Var, custom_record) 一样测试您的变量。

    【讨论】:

    • 更好的是is_record/3,至少如果你知道你正在使用的所有记录的大小,因为它不需要知道记录定义。
    【解决方案2】:

    Erlang 中没有自定义类型。记录只是用原子标记且长度相同的元组的语法糖。类型规范仅由透析器使用,没有其他用途。

    【讨论】:

      【解决方案3】:

      您可以为此使用模式匹配:

      is_custom_type(#custom_record{} = _Record) -> true;
      is_custom_type(_) -> false.
      

      【讨论】:

      • 这样做的缺点是对于属于该类型的每条记录都需要一个函数子句。在我的示例中只有两条记录,但在我的部分代码中却有不少。
      • 那么您要求的功能对您有何帮助?
      猜你喜欢
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 2018-09-09
      • 2021-10-26
      • 2020-07-02
      相关资源
      最近更新 更多