Reputation: 45
How I understood, -spec
uses in Erlang for dialyzer only.
How can I check type (e.g. in function) at compile time (how this is realize e.g. in Haskell)?
Upvotes: 3
Views: 5705
Reputation: 4906
@zxq9 is right. You can't. However, I wanted to add that in addition to dialyzer, you can also add guards to your function definitions. Dialyzer is great for static analysis but doesn't help at runtime. In addition to defining the function and the type spec, like this:
-spec foo(X :: integer()) -> integer().
foo(X) -> X + 1.
You can also add a guard condition in the function definition:
-spec foo(X :: integer()) -> integer().
foo(X) when is_integer(X) -> X + 1.
This ensures that an exception is raised if an unexpected type is passed to the function call. By using both type specs and guards you can ensure that function will only be invoked on the specified type.
Upvotes: 2
Reputation: 13154
Short answer: you can't.
Erlang is a dynamically typed language and many of the assumptions the runtime depends on require it to be that way, at least in some places. There have been discussions in the past about making a strongly-typed subset or functionally pure subset of the language, but neither approach has demonstrated itself to be worth the effort beyond what dialyzer already provides.
That said, dialyzer is a tremendously useful tool if you structure your code to take advantage of it.
Upvotes: 4