OCaml - What is an unsound type?

瘦欲@ 提交于 2019-12-03 12:07:44

How Warning 21 is reported

First, let's think of functions which returns unrelated 'a: I do not mean function like let id x = x here since it has type 'a -> 'a and the return type 'a relates with the input. I mean functions like raise : exn -> 'a and exit : int -> 'a.

These functions return unrelated 'a are considered never returning. Since the type 'a (more precisely forall 'a. 'a) has no citizen. Only thing the functions can do are terminating the program (exit or raising an exception) or falling into an infinite loop: let rec loop () = loop ().

Warning 21 is mentioned when the type of a statement is 'a. (Actually there is another condition but I just skip for simplicity.) For example,

# loop (); print_string "end of the infinite loop";;
Warning 21: this statement never returns (or has an unsound type.)

This is the main purpose of warning 21. Then what is the latter half?

"Unsound type"

Warning 21 can be reported even if the statement returns something actually. In this case, as the warning message suggests the statement has a unsound type.

Why unsound? Since the expression does return a value of type forall 'a. 'a, which has no citizen. It breaks the basis of the type theory OCaml depends on.

In OCaml, there are several ways to write an expression with such an unsound type:

Use of Obj.magic. It screws type system therefore you can write an expression of type 'a which returns:

(Obj.magic 1); print_string "2"

Use of external. Same as Obj.magic you can give arbitrary type to any external values and functions:

external crazy : unit -> 'a = "%identity"
let f () = crazy ()  (* val f : unit -> 'a *)
let _ = f (); print_string "3"

For OCaml type system, it is impossible to distinguish non-returning expressions and expressions with unsound types. This is why it cannot rule out unsound things as errors. Tracking the definitions to tell a statement has an unsound type or not is generally impossible either and costs a lot even when possible.

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