if-expressions

Chris Nicholson-Sauls ibisbasenji at gmail.com
Mon May 28 02:04:50 PDT 2007


Bent Rasmussen wrote:
> I've been away from D for quite a while, but am anxious to get back and 
> use the new features.
> 
> Reading the newsgroup to catch up a little, I remembered a feature of 
> another language (haXe) I've been using for some light-weight work. It 
> has the nice property that `if´ is an expression. So I was wondering if 
> this would be nice in D as well...
> 
> int lim(int x, int a, int b)
> {
>    return if (x < a)
>        a
>    else if (x > b)
>        b
>    else
>        x;
> }

Or Ruby:
# return if x < a then a
#     elsif x > b then b
#                 else x
# end

> But it could also be written
> 
> int lim(int x, int a, int b)
> {
>    return x < a ?
>        a
>    : x > b ?
>        b
>    :
>        x;
> }
> 
> The question is if very nested ?: expressions will look very readable, 
> in isolation and compared to if's.

I find myself using this from time to time, and the readability goes hand-in-hand with 
layout.  I tend to write them closer to this:

# return
#   x < a
#     ? a
#     : x > b
#         ? b
#         : x
# ;

So that the "choice" operators '?' and ':' are at the beginnings of lines.  This makes it 
trivial for me to pick out what I care about when re-reading code.

> I've found if-expressions to be changing my coding style and making my 
> code cleaner and a lot more readable. The same goes for 
> switch-expressions. Many functions have turned into pure expressions 
> with just one point of return.
> 
> I'll try and recode some libraries using ?: expressions to begin with 
> and see how it shapes up visually.
> 
> If this all sounds stupid, be gentle, I'm just returning to the D game 
> again. :-)
> 
> Regards
> Bent
> 

I'm still neutral on if-expressions, although maybe a sub-syntax to enable them would be 
useful.  What I /am/ quite fond of, is expression modifiers as if's (and others).  Things 
like:

parseLine unless /^$/

(Where 'unless' is Ruby's equivelant to if(!...).)  Of course, the Ruby manual warns 
against the kinds of craziness that abuse of these kind of features can lead to.  Imagine 
the poor maintenance programmer who comes along and finds lots of:

# while artist = nextArtist
#   (artist.quick_name = nick) if nick = db.alias(artist)
# end unless nicknames == "no"

o_O``  (Slightly further barf'ing of an example from the Ruby docs.)

It might really just be too much for a native/static language such as D.  These are the 
sort of things that I don't imagine play well at all outside of a managed/VM environment.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list