Ocaml 嵌套 if 没有 else

Ocaml nested if without else

如果没有 else 语句,是否可以嵌套。我编写了以下无用的程序来演示嵌套的 ifs。我该如何解决这个问题,使其在语法方面是正确的。第 5 行和第 6 行给出错误。

let rec move_helper b sz r = match b with
    [] -> r
    |(h :: t) ->
        if h = 0 then
            if h - 1 = sz then h - 1 ::r
            if h + 1 = sz then h + 1 ::r
        else move_helper t sz r
;;

let move_pos b = 
    move_helper b 3 r
;;

let g = move_pos [0;8;7;6;5;4;3;2;1]

没有 else 就不能有 if,除非表达式的结果是 unit 类型。你的代码不是这种情况,所以这是不可能的。

这是一个示例,其中结果为 unit:

let f x =
    if x land 1 <> 0 then print_string "1";
    if x land 2 <> 0 then print_string "2";
    if x land 4 <> 0 then print_string "4"

您必须了解 if ... then 是一个与其他表达式一样的表达式。如果不存在 else,则它必须被理解为 if ... then ... else (),因此类型为 unit。为了强调它是一个表达式这一事实,假设您有两个函数 fg,类型为 int → int。你可以写

(if test then f else g) 1

您还必须了解 x :: r 根本 不会 改变 r,它构建了一个新列表,将 x 放在前面r(此列表的尾部与列表 r 共享)。在您的情况下,逻辑不清楚: h=0 但两个 if 失败时的结果是什么?

let rec move_helper b sz r = match b with
  | [] -> r
  | h :: t ->
     if h = 0 then
       if h - 1 = sz then (h - 1) :: r
       else if h + 1 = sz then (h + 1) :: r
       else (* What do you want to return here? *)
     else move_helper t sz r

当你有 if 时,一定要加上 else。因为当你不放else的时候,Java就不知道是真是假了。