我可以定义一个返回自身的OCaml函数吗?

9
在Scheme中,我可以编写一个函数:
(define (eat-line line)
  eat-line)

我可以在循环中使用它,例如:

(define (loop op)
  (let ((line (read-line))
    (loop (op line))))

在OCaml中,我尝试定义一个函数:

let rec eat_line line = eat_line

但是我遇到了错误:
Error: This expression has type 'a -> 'b
   but an expression was expected of type 'b
   The type variable 'b occurs inside 'a -> 'b

在OCaml中定义这样的函数是否可能,或者被类型系统阻止了?如果是这样,为什么?
1个回答

12

如果您在运行解释器或编译器时指定了-rectypes,则可以定义该函数:

$ ocaml -rectypes
        OCaml version 4.01.0

# let rec eat_line line = eat_line;;
val eat_line : 'b -> 'a as 'a = <fun>

# eat_line "yes" "indeed";;
- : string -> 'a as 'a = <fun>
# eat_line 3 5 7;;
- : int -> 'a as 'a = <fun>

默认情况下,不允许使用这样的类型(递归或循环类型),因为它们往往是编码错误的结果。


1
非常感谢您的惊人迅速回答! - Jonathan Chan
1
对于读者:这个问题在15年前已经讨论过了:http://caml.inria.fr/pub/old_caml_site/caml-list/2040.html - Str.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接