ocaml - 为什么这个 OCaml 代码收到 "Unexpected token"?

标签 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 行中获取“意外 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 中的表达式,它采用值 barqux。因此 barqux 需要具有相同的类型。
  • 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/

相关文章:

types - 在定义它们的模块之外使用开放联合

functional-programming - 在函数式编程中,什么是仿函数?

haskell - 将 OCaml 代码与共享库链接

recursion - 变体、递归函数和类型推断

list - 如何可靠地比较列表的整数或浮点值?

ocaml - OCaml中的条件编译

haskell - OCaml 仿函数、Haskell 类型类和多重派生

OCaml : filter map and put the values into a list

ocaml - 在 OPAM 中切换环境

list - 笛卡尔积类型错误