Syntax of nested "if else" in SML

Kamath picture Kamath · Jan 21, 2013 · Viewed 13.3k times · Source

I am strugging a bit to implement a nested if else expressions in SML. Can anyone highlight its syntax. Suppose there are three conditions C1, C2, C3 I need equivalent of following in C code.

if (C1) { 
    return true;
}
else {
    if(C2) {
        return true;
    }
    else {
         if (C3) {
             return true;
         }
         else {
             return false;
         }
    }
}

I tried the following, but its treated as "if, else if, and else" cases

if C1 then true
else if C2 then true
else if C3 then true
else false

Answer

pad picture pad · Jan 21, 2013

You're correct. Two code fragments are equivalent.

With a bit of indentation, your SML example looks more like using nested if/else:

if C1 then true
else
    if C2 then true
    else
        if C3 then true
        else false

You could also use parentheses so that SML example looks almost the same as C example but it isn't necessary.

Of course, the most idiomatic way in SML is to write

C1 orelse C2 orelse C3

You could use the same trick for your C code. Remember that returning true/false in if/else blocks is code smell.