Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the -spec functionality in erlang

I'm writing up a small erlang service and I would like to put constraints on my types.

I've found the -spec functionality, and it looks to me like this is a way of 'locking' the signatures of functions to specific types.

My example would be a function like:

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

adding the line

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

should make sure the method atleast returns the correct type, but this does not seem to be the case..

for If I change the function to :

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

the code still compiles, fine and even runs.

What am I misunderstanding?

like image 657
Martin Kristiansen Avatar asked Dec 14 '11 13:12

Martin Kristiansen


People also ask

How do I run Erlang function?

On a Unix system you enter the command erl at the operating system prompt. This command starts the Erlang runtime system and the Erlang shell. On the Windows platform you normally start Erlang/OTP from the start menu. You can also enter the command erl or werl from a DOS box or Command box.

How do you declare a variable in Erlang?

In Erlang, all the variables are bound with the '=' statement. All variables need to start with the upper case character. In other programming languages, the '=' sign is used for the assignment, but not in the case of Erlang. As stated, variables are defined with the use of the '=' statement.

What type of variables are used in Erlang?

Variables can contain alphanumeric characters, underscore and @. Variables are bound to values using pattern matching. Erlang uses single assignment, that is, a variable can only be bound once. The anonymous variable is denoted by underscore (_) and can be used when a variable is required but its value can be ignored.

How many types of Erlang are there?

7 Types and Function Specifications.


1 Answers

Compiler skips those comments. But you can use dialyzer to do static code analysis. This tool will warn you about spec violations.

like image 188
werewindle Avatar answered Oct 10 '22 14:10

werewindle