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

4

2 回答 2

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 吗?我建议您先定义一个 sum 类型pos并对其进行模式匹配。

于 2013-01-19T23:11:26.467 回答
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的 s 之前移动您的ins:

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 ...

(我希望这是有帮助的。)

于 2013-01-19T23:13:09.703 回答