How to use -spec functionality in erlang

I am writing a small erlang service and I would like to set restrictions on my types.

I found the functionality - spec , and it seems to me that this is a way to "block" function signatures for certain types.

My example would be a function such as:

fib(N) when N < 3 ->
    1;
fib(N) ->
    fib(N-1) + fib(N-2).

adding a line

-spec fib_cps(pos_integer()) -> pos_integer().

should make sure the atleast method returns the correct type, but that doesn't seem to be the case.

for If I change the function to:

fib(N) when N < 3 ->
    ok;
fib(N) ->
    not_ok.

the code is still compiling, executing fine, and even executing.

What? I do not understand?

+5
source share
2 answers

. . .

+11

werewindle , -spec , . , . , :

fib(N) when is_integer(N), N > 0, N < 3 ->
    1;
fib(N) when is_integer(N), N >= 3 ->
    fib(N-1) + fib(N-2).

, , :

fib(1) -> 1;
fib(2) -> 1;
fib(N) when is_integer(N), N >= 3 ->
    fib(N-1) + fib(N-2).

- fib(bogus) fib(0.5) fib(-1). , badmatch .

. , guard, , . erlang.

+1

All Articles