Cyclic type definition in OCaml

一曲冷凌霜 提交于 2020-01-04 09:37:53

问题


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

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