#MonthOfJulia Day 8: Iteration, Conditionals and Exceptions
Yesterday I had a look at Julia’s support for Functional Programming. Naturally it also has structures for conventional program flow like conditionals, iteration and exception handling.
Conditionals allow you to branch the course of execution on the basis of one or more logical outcomes.
The ternary conditional operator provides a compact syntax for a conditional returning one of two possible values.
I’m still a little gutted that R does not have a ternary operator. Kudos to Python for at least having something similar, even if the syntax is somewhat convoluted.
There are a few different ways of achieving iteration in Julia. The simplest of these is the humble
In the code above we used the range operator,
:, to construct an iterable sequence of integers between 1 and 10. This might be a good place to take a moment to look at ranges, which might not work in quite the way you’d expect. To get the range to actually expand into an array you need to enclose it in
, otherwise it remains a
for loop can iterate over any iterable object, including strings and dictionaries. Using
enumerate() in conjunction with a for loop gives a compact way to number items in a collection.
while construct gives a slightly different approach to iteration and is probably most useful when combined with
break statements which can be used to skip over iterations or prematurely exit from the loop.
The details of exception handling are well covered in the documentation, so I’ll just provide a few examples. Functions generate exceptions when something goes wrong.
All exceptions are derived from the
Exception base class.
An exception is explicitly launched via
throw(). To handle the exception in an elegant way you’ll want to enclose that dodgy bit of code in a
Exceptional conditions can be flagged by the
error() function. Somewhat less aggressive are
I’ve dug a little deeper into conditionals, loops and exceptions in the code on github.