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 行中获取“意外 token ”。我的错误是什么?
最佳答案
这是一个可以编译的代码:
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
- 您不需要类型注释:OCaml 具有类型推断
- if 子句不需要括号
new_forward 位置
有拼写错误
此外,根据您的代码逻辑,let _ = move_robot 0 "forward"5
会失败。它不应该返回 5 吗?我建议您为 pos
定义一个求和类型,并首先对其进行模式匹配。
关于ocaml - 为什么这个 OCaml 代码收到 "Unexpected token"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14419750/