Motoko Coalescing Operator

I have read that there is no ternary operator for Motoko (Ternary operator), but is there a null coalescing operator or a more succinct expression than an inline if statement?

Examples:

There is a get function for option types documented here: Option :: Internet Computer

So get(x, d) where x is an option type returns x if x is not null or d if x is null. That is what you wanted, or?

1 Like

Yes, that is exactly what I was looking for! Thank you!

Please read that thread to the enf, @kritzcreek corrected the response: there is a “ternary operator” in Motoko, but it’s simply called if:

let a = if b {1} else {2}

Thank you for the clarification Mr. Rossberg. I read that post, but did not think that an if/else statement could be considered a ternary operator. However, I see that the inline behavior is the subtle difference that makes that variation of an if/else a ternary operator.

Strictly speaking, there are no statements in Motoko, everything is an expression. That includes things like if and switch, which can return a value:

let a = switch x { case null {1}; case (?y) {y} }
1 Like

That is very useful. Thanks again! I would love to know the influence/motivation behind that language design choice if it’s possible to put in layman’s terms.

It’s always been standard in functional programming languages, all the way back to Lisp in 1958 and ISWIM in 1966. But even the good old procedural Algol 68 already worked that way.

The statement/expression distinction has always been an artificial and pointless restriction, and it’s rather puzzling to me that it still persists in so many mainstream languages. :wink:

3 Likes

Thank you for raising my awareness on the history of these expressions. I am very mainstream (pays the bills), but I always look forward to learning more about Motoko after work. I really appreciate your time and assistance Mr. Rossberg!

1 Like