为什么这个OCaml代码收到“意外令牌”?

时间:2013-01-19 22:51:10

标签: ocaml

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行获取“意外令牌”。我的错误是什么?

2 个答案:

答案 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中的表达式,其值为barqux。因此barqux需要具有相同的类型。
  • new_backward_position代替new_backward_position pos
  • 您不需要类型注释:OCaml具有类型推断
  • 围绕if子句
  • 不需要括号
  • 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 ...

(我希望这很有帮助。)