简体   繁体   中英

Ocaml nested if without else

Is it possible to have nested if without else statements. I wrote the following useless program to demonstrate nested ifs. How do I fix this so it's correct in terms of syntax. lines 5 and 6 gives errors.

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]

You can't have if without else unless the result of the expression is of type unit . This isn't the case for your code, so it's not possible.

Here's an example where the result is 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"

You must understand that if ... then is an expression like any other. If no else is present, it must be understood as if ... then ... else () and thus has type unit . To emphasize the fact that it is an expression, suppose you have two functions f and g of type, say, int → int . You can write

(if test then f else g) 1

You must also understand that x :: r does not change r at all, it constructs a new list putting x in front of r (the tail of this list is shared with the list r ). In your case, the logic is not clear: what is the result when h=0 but the two if fail?

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

When you have a if, always put an else. Because when you don't put an else, Java will not know if the case is true or false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM