[erlang-questions] is it possible to reuse a "-type" specification for a function in a "-spec" ?

Kostis Sagonas <>
Thu Jul 28 07:25:17 CEST 2016


On 07/20/2016 10:21 PM, Marco Molteni wrote:
> Hello,
>
> say I have a function that takes a function as an argument and I want
> to write type specifications for them:
>
>    -type decider() :: fun((pos_integer(), #node{}) ->
>        reject | accept | continue).
>
>    -spec foo(Decider :: decider()) -> boolean().
>    foo(Decider) -> ...
>
> When implementing the callback, I would like to reuse the type decider():
>
> Instead of duplicating the same type information (error prone, can go
> out of sync):
>
>    -spec my_cb(pos_integer(), #node{}) -> reject | accept | continue.
>    my_cb(X, Tree) -> ...
>
> I would like to write something like:
>
>    -spec my_cb :: decider().
>    my_cb(X, Tree) -> ...
>
> Is there a way?

Yes, an ugly one, using macros.

I would not recommend using that option though.

Kostis

PS. Some of the duplication in your example, can be avoided in a nice 
way by giving names to types.  For example, you can define:

-type node_rec()    :: #node{}.
-type decider_ret() :: reject | accept | continue.
-type decider_fun() :: fun((pos_integer(),node_rec()) -> decider_ret()).


More information about the erlang-questions mailing list