monte-language / monte

A dynamic language inspired by Python and E.
Other
79 stars 11 forks source link

`return if` parser support #37

Closed MostAwesomeDude closed 8 years ago

MostAwesomeDude commented 10 years ago

A common pattern in C and other languages that support a ternary boolean operator is to assign the result of a ternary operation to a variable or return a result from a function:

int increment = count > 5 ? 2 : 1;

char* even(int i) {
    return i % 2 ? "no" : "yes";
}

Monte lacks the ternary operator, but permits using regular conditional expressions in its place:

increment :int := if (count > 5) { 2 } else { 1 }

def even(i :int) :String:
    return if (i % 2 == 0):
        "yes"
    else:
        "no"

Note that Monte requires the first component of its conditional expressions to evaluate to a boolean object; no automatic coercion is done.

MostAwesomeDude commented 9 years ago

Updating for modern Monte guard names. Also somebody pointed out that the parser doesn't work correctly here.

increment :Int := if (count > 5) { 2 } else { 1 }

def even(i :Int) :Str:
    return if (i % 2 == 0):
        "yes"
    else:
        "no"
edunham commented 9 years ago

Actually it does work, when you use braces and no guards:

def even(i):
    return if (i % 2 == 0) { "yes" } else { "no"}

I'd be inclined to blame problems with the non-oneliner version on other parts of the parser, but then again I haven't dug around in its guts very much.