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

时间:2014-12-28 09:03:34

标签: ocaml

在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 个答案:

答案 0 :(得分: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>

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