【问题标题】:Multiple specifications for same function in Erlang header fileErlang 头文件中同一函数的多个规范
【发布时间】:2022-01-13 19:42:44
【问题描述】:

我正在尝试在头文件中指定一个函数。 像这样:

-spec update(pid(), tuple(tuple(), integer(), atom()), tuple(atom(), atom())) -> tuple(tuple(), integer(), atom()).

现在我想为这个函数添加一些额外的规范,因为它有多个不同的参数。

update(_Pid, {Specs, infinity, _State}, {Step}) ->
  timer:sleep(10000),
  {{Specs, infinity}, {Step}};
update(_Pid, {Specs, infinity, _State}, {ExtraInfo, Step}) ->
  timer:sleep(10000),
  {{Specs, infinity}, {ExtraInfo, Step}};
update(_Pid, {Specs, N, _State}, _Info) when N < 2 ->
  {Specs, N, stop};
update(_Pid, {Specs, N, _State}, {notTaken, Step}) ->
  {Specs, N, Step};
update(_Pid, {Specs, N, _State}, {taken, Step}) ->
  {Specs, N - 1, Step}.

所以我想在我的头文件中为这个函数中的不同参数添加这些额外的规范。我不知道该怎么做,有人可以帮我吗?

我尝试这样做,但它给了我编译错误:

-spec update(pid(), tuple(tuple(), integer(), atom()), tuple(atom(), atom())) -> tuple(tuple(), integer(), atom()).
-spec update(pid(), tuple(tuple(), atom(), atom()), tuple(integer(), atom())) -> tuple(tuple(), atom(), atom()).
-spec update(pid(), tuple(tuple(), atom(), atom()), tuple(atom())) -> tuple(tuple(), atom(), atom()).

提前致谢。

【问题讨论】:

    标签: erlang


    【解决方案1】:

    我找到了答案here。我不得不使用分号;。我改变了这个:

    -spec update(pid(), tuple(tuple(), integer(), atom()), tuple(atom(), atom())) -> tuple(tuple(), integer(), atom()).
    -spec update(pid(), tuple(tuple(), atom(), atom()), tuple(integer(), atom())) -> tuple(tuple(), atom(), atom()).
    -spec update(pid(), tuple(tuple(), atom(), atom()), tuple(atom())) -> tuple(tuple(), atom(), atom()).
    

    进入这个:

    -spec update(pid(), tuple(tuple(), integer(), atom()), tuple(atom(), atom())) -> tuple(tuple(), integer(), atom());
                (pid(), tuple(tuple(), atom(), atom()), tuple(integer(), atom())) -> tuple(tuple(), atom(), atom());
                (pid(), tuple(tuple(), atom(), atom()), tuple(atom())) -> tuple(tuple(), atom(), atom()).
    

    【讨论】:

    • 没错。不过,我能问一下你为什么要把它放在头文件中吗?
    • 为了让我的代码更加健壮,并且它具有可以复制的功能。
    • 您是否考虑过使用带有行为的-callback 机制?它们允许您将类型规范放在行为定义上,而不是在许多地方重复。
    • 我已经搜索过了,但我认为我的情况没有必要(无论如何现在)。但是感谢您的建议
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2019-04-19
    • 2022-06-10
    • 1970-01-01
    相关资源
    最近更新 更多