Ocaml can';t定义一个新变量来保存我的rlist
我正在学习Ocaml中的命令式编程,在以下情况下,我试图反转链接列表: 以下是我定义的两种类型:Ocaml can';t定义一个新变量来保存我的rlist,ocaml,Ocaml,我正在学习Ocaml中的命令式编程,在以下情况下,我试图反转链接列表: 以下是我定义的两种类型: type cell = { data : int; next : rlist; } and rlist = cell option ref 这是我的函数: let reverse (head:rlist) = let rec helper ((head: rlist),(tmp: rlist)) = match !head with | None -> tmp
type cell = { data : int; next : rlist; }
and rlist = cell option ref
这是我的函数:
let reverse (head:rlist) =
let rec helper ((head: rlist),(tmp: rlist)) =
match !head with
| None -> tmp
| Some c when !(c.next) = None ->
c.next := !tmp ; tmp := Some c ; tmp
| Some c ->
let a = ref Some !(c.next) ;
c.next := !tmp ;
tmp := Some c ;
helper (a,tmp)
in
helper (head, ref None)
这个版本会给我语法错误,但如果我替换:let a=ref Some!(c.next)
带头:=!(c.next)
它会工作的。因此,我的let声明有问题。此表达式:
ref Some !(c.next)
let a = ref (Some !(c.next));
解析如下:
(ref Some) !(c.next)
ref (Some !(c.next))
本质上是因为OCaml中的函数应用程序具有非常高的优先级
您应该像这样插入括号:
(ref Some) !(c.next)
ref (Some !(c.next))
解决此问题后,您会遇到另一个语法问题。这句话:
ref Some !(c.next)
let a = ref (Some !(c.next));
无效。您需要在let
之后的中加入。简短的描述是,在函数中,let
用于引入局部变量,使用局部变量的表达式出现在
中的之后。需要
中的。您可以通过更改
在
中的末尾
修复这两个语法问题后,您至少有一个类型错误。但我希望这能帮助你取得进步。这个表达:
ref Some !(c.next)
let a = ref (Some !(c.next));
解析如下:
(ref Some) !(c.next)
ref (Some !(c.next))
本质上是因为OCaml中的函数应用程序具有非常高的优先级
您应该像这样插入括号:
(ref Some) !(c.next)
ref (Some !(c.next))
解决此问题后,您会遇到另一个语法问题。这句话:
ref Some !(c.next)
let a = ref (Some !(c.next));
无效。您需要在let
之后的中加入。简短的描述是,在函数中,let
用于引入局部变量,使用局部变量的表达式出现在
中的之后。需要
中的。您可以通过更改
在
中的末尾
修复这两个语法问题后,您至少有一个类型错误。但我希望这能帮助你取得进步