问题
Obviously the following type definition is cyclic
:
type node = int * node;;
Error: The type abbreviation node is cyclic
My question is how comes the following one is not cyclic
?
type tree = Node of int * tree;;
The second definition also refers to itself.
回答1:
One way to look at it is that node
is an abbreviation for a type, not a new type itself. So the compiler (or anybody who's interested) has to look inside to see what it's an abbreviation for. Once you look inside you start noticing things that make it difficult to analyze (e.g., that it's a recursive type and hence can require many unfoldings).
On the other hand, tree
is a new type that's characterized by its constructors. (In this case, just the one constructor Node
). So the compiler (or other interested party) doesn't need to look inside at all to determine what the type is. Once you see Node
the type is determined. Even if you do look inside, you only need to look down one level. This allows recursion without causing any difficulties in analysis.
As a practical matter, recursive types of the first sort are often unintentional, and they lead to strange typings. The second sort are virtually impossible to create by mistake because of the little signposts (constructors) all along the way; in fact they're kind of like the lifeblood of the type system.
来源:https://stackoverflow.com/questions/22093873/cyclic-type-definition-in-ocaml