Main Site

This is Gem Newman's blog. Return to the main site.

Quotation

19 August 2011

Stand back: I'm going to try Boolean logic!

Fair warning: unless you're really into hardcore computer geekery, you're probably going to want to ignore this post. This has nothing much to do with skepticism, so feel free to skip it.

I do a lot of work in MATLAB, a programming language not without its quirks. One of its (many) missing features is the ternary operator, also known as the inline if statement. I'll give you a trivial example.

In many languages, you can do something like this:

fprintf(file, 'The statement is %s!\n', statement ? 'true' : 'false');

In MATLAB, however, you have to do this:

if statement
    fprintf(file, 'The statement is true!\n');
else
    fprintf(file, 'The statement is false!\n');
end

Even if you don't understand the statements above, you probably get the idea. The first one is a lot more succinct than the second. There are cases in which you would need to completely restructure your function in order to remove a ternary operator. Although the uses of this operator are fairly esoteric, suffice it to say that this is a useful feature to have.

I came across a problem which really needed to be solved with an inline if. I was fooling around with function handles, and eventually came up with the following (warning: MATLAB code ahead):

iif = @(condition, ifTrue, ifFalse)(feval(@ result, trueOrFalse)(result{trueOrFalse + 1}), {ifFalse ifTrue}, condition));

Yes, that is a function handle declaration with a nested anonymous function. If you're not accustomed to dealing with function handles, I wouldn't be offended if you bowed out now.

In any event, this code allows me to replicate the inline if functionality that MATLAB is missing! Observe:

fprintf(file, 'The statement is %s!\n', iif(statement, 'true', 'false'));

Not bad! Needless to say, I felt pretty good about myself.

Of course, my friend Curt had to come along and burst my bubble. He pointed out that I was so obsessed with writing things in one line that I'd overlooked the fact that I could have just as easily written iif as a standard function and still used it as an inline if:

function result = iif(condition, ifTrue, ifFalse)
    if condition
        result = ifTrue;
    else
        result = ifFalse;
    end
end

I can still execute the iif function in one line, as above, but this version is clearly easier to read. I benchmarked the two of them several times with 10,000 random comparisons that evaluated to true or false. The function version of iif completed the benchmark in under 0.1 seconds, while the evaluating the function handle took a dismal 2.2 seconds.

Blast.

1 comment:

  1. Ha. That one made me smile.
    It always frustrates me when an otherwise decent language skips out on things you simply expect to be there. But at least you don't have True and False being equal to -1 and 0 respectively...
    (thankfully, neither do I)

    ReplyDelete