let rec move_robot (pos: int) (dir: string) (num_moves: int) : int =
let new_forward_position = pos + num_moves in
if (new_forward_position > 99) then failwith "cannot move beyond 99 steps"
else new_forward_position
let new_backward_position = pos - num_moves in
if (new_backward_position pos < 0) then failwith "cannot move less than 0 steps"
else new_backward_position
begin match dir with
| "forward" -> new_forward position
| "backward" -> new_backward_position
end
我继续为let new_backward_position行获取“意外令牌”。我的错误是什么?
答案 0 :(得分:3)
这是一个编译代码:
let rec move_robot pos dir num_moves =
let new_forward_position = pos + num_moves in
if new_forward_position > 99 then failwith "cannot move beyond 99 steps";
let new_backward_position = pos - num_moves in
if new_backward_position < 0 then failwith "cannot move less than 0 steps";
begin match dir with
| "forward" -> new_forward_position
| "backward" -> new_backward_position
end
我修改了几件事:
if foo then bar else qux
是OCaml中的表达式,其值为bar
或qux
。因此bar
和qux
需要具有相同的类型。new_backward_position
代替new_backward_position pos
new_forward position
此外,根据您的代码逻辑,let _ = move_robot 0 "forward" 5
失败。不应该返回5而不是吗?我建议你为pos
定义一个和类型,然后先对它进行模式匹配。
答案 1 :(得分:2)
如果您认为不会发生故障,则您的代码具有此基本结构:
let f () =
let p = 3 in p
let q = 5 in q
...
目前还不清楚你要做什么,但这不是很好的OCaml(正如编译器告诉你的那样)。也许你想要的更像是这样的东西:
let f () =
let p = 3 in
let q = 5 in
match ...
如果是这样,您需要在if
之前移动in
:
let f () =
let p = if badp then failwith "" else 3 in
let q = if badq then failwith "" else 5 in
match ...
或者这可能更符合您的要求:
let f () =
let p = 3 in
let () = if badp p then failwith "" in
let q = 5 in
let () = if badq q then failwith "" in
match ...
(我希望这很有帮助。)