Erlang type system

廉价感情. 提交于 2019-12-09 15:09:59

问题


I've been scrounging around the web looking for various typing practices of Erlang programs and there seem to be a few... although its somewhat difficult to find a solid source of info namely Im looking for practical info about:

1.-specs - this one looks pretty attractive. a few places mention that the functions that have an associated -specs directive with it are checked at compile time(for correct type usage)... I cant seem to find more info on how to use it (which tool to use - Dialyzer,TypEr?). Im really eager to create a small parser/code-gen that would generate these "specs" from function declarations of the form

functionName(param1 :List, param2 :Tuple) -> ...

I have not seen if -spec supports abstract types (user declared types - "Car" type -

{car,{weight,_},{height,_},{maxSpeed,_}}

2.-deftype directive mentioned here

Erlang would become so much more powerful for me, if I could start typing things and have them be checked at compile time. The run-time the parser/code-gen I mentioned above would generate guard type checks in the output source-code.


回答1:


More info on the type and spec attributes here:

http://www.erlang.org/eeps/eep-0008.html

Dialyzer can be used to check them (see dialyzer --help).

Typer can be used to generate them (see typer --help).




回答2:


Take a look to http://learnyousomeerlang.com/types-or-lack-thereof (very clean explanation) and the reference here: http://erlang.org/doc/reference_manual/typespec.html




回答3:


Compile time type checking is not the done thing with Erlang. Instead use the Dialyzer which performs post-compile type checking.

The way in which you create 'user-defined types' is by using tagged tuples as you suggest. The Dialyzer will examine code paths to identify ones that MIGHT end up creating function returns that fail.

For the dialyzer to work best you must embrace 'let if fail' and only write clauses that match the expected results - eschew 'else' constructs that always match and a few other best practices.

You should document your functions with edoc. The dialyzer uses the type specification of the document system to infer types for you. The edoc manual can be found here.



来源:https://stackoverflow.com/questions/532176/erlang-type-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!