Kamath
Kamath

Reputation: 4664

Syntax of nested "if else" in SML

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

Upvotes: 3

Views: 18752

Answers (2)

brunsgaard
brunsgaard

Reputation: 5158

I agree that using orelse is the right way to go here, but just as an alternative to situations where you want to act on more complex combinations, pattern matching would be able to help you.

fun funtrue (false,false,false) = false
  | funtrue _                   = true

or as a case statement

case (C1,C2,C3) of
     (false,false,false) => false
  |  _                   => true

Upvotes: 3

pad
pad

Reputation: 41290

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.

Upvotes: 11

Related Questions