# Introducing Julia/Controlling the flow
### Different ways to control the flow

Typically each line of a Julia program is evaluated in turn. There are various ways to control and modify the flow of evaluation. These correspond with the constructs used in other languages:
* ternary and compound expressions
* Boolean switching expressions
* if elseif else end — conditional evaluation
* for end — iterative evaluation
* while end — iterative conditional evaluation
* try catch error throw exception handling
* do blocks

### Ternary expressions

Often you'll want to do job A (or call function A) if some condition is true, or job B (function B) if it isn't. The quickest way to write this is using the ternary operator ("?" and ":"):
Here's another example:
and Julia returned the value of sin(x), because x was less than 0.5. cos(x) wasn't evaluated at all.

### Boolean switching expressions

Boolean operators let you evaluate an expression if a condition is true. You can combine the condition and expression using && or ||. && means "and", and || means "or". Since Julia evaluates expressions one by one, you can easily arrange for an expression to be evaluated only if a previous condition is true or false.
The following example uses a Julia function that returns true or false depending on whether the number is odd: isodd(n).
With &&, both parts have to be true, so we can write this:
If the first condition (number is odd) is true, the second expression is evaluated. If the first isn't true, the expression isn't evaluated, and just the condition is returned.
With the || operator, on the other hand:
If the first condition is true, there's no need to evaluate the second expression, since we already have the one truth value we need for "or", and it returns the value true. If the first condition is false, the second expression is evaluated, because that one might turn out to be true.
This type of evaluation is also called "short-circuit evaluation".

### If and Else

For a more general — and traditional — approach to conditional execution, you can use if, elseif, and else. If you're used to other languages, don't worry about white space, braces, indentation, brackets, semicolons, or anything like that, but remember to finish the conditional construction with end.
The elseif and else parts are optional too:
Just don't forget the end!
How about 'switch' and 'case' statements? Well, you don't have to learn the syntax for those, because they don't exist!

#### ifelse

There's an ifelse function, too. It looks like this in action:
ifelse is an ordinary function, which evaluates all the arguments, and returns the second or third, depending on the value of the first. With the conditional if or ? ... :, only the expressions in the chosen route are evaluated. Alternatively, it is possible to write things like:

### For loops and iteration

Working through a list or a set of values or from a start value to a finish value are all examples of iteration, and the for ... end construction can let you iterate through a number of different types of object, including ranges, arrays, sets, dictionaries, and strings.
Here's the standard syntax for a simple iteration through a range of values:
The variable i takes the value of each element in the array (which is built from a range object) in turn — here stepping from 0 to 100 in steps of 10.
We haven't yet met sets and dictionaries, but iterating through them is exactly the same.
You can iterate through a 2D array, stepping "down" through column 1 from top to bottom, then through column 2, and so on:
You can use = instead of in.

##### Iterating over an array and updating it

When you're iterating over an array, the array is checked each time through the loop, in case it's changed. A mistake you should avoid making is to use push! to make an array grow in the middle of a loop. Run the following text carefully, and be ready to Ctrl-C when you've seen enough (otherwise your computer will eventually crash):

#### Loop variables and scope

The variable that steps through each item—the 'loop variable'—exists only inside the loop, and disappears as soon as the loop finishes.
If you want to remember the value of the loop variable outside the loop (eg if you had to exit the loop and needed to know the value you'd reached), use the global keyword to define a variable that outlasts the loop.
Here, howfar didn't exist before the loop, but it survived to tell its story when the looping was over. If howfar existed before the loop started, you can change its value only if you use global in the loop.
Working in the REPL is slightly different from how you write code inside functions. In a function, you would write this:

#### Variables declared inside a loop

In a similar way, if you declare a new variable inside a loop, it won't exist once the loop finishes. In this example, k is created inside:
so it doesn't exist after the loop has finished:
Variables created inside one iteration of a loop are forgotten at the end of each iteration. In this loop:
z is created afresh each time. If you want a variable to persist from iteration to iteration, it has to be global:
To see this in more detail, consider the following code.
Perhaps you expected only the first loop to produce the "z isn't defined error"? In fact, even if z is created in the body of the loop, it is undefined at the start of the next iteration.
Again, use the global keyword to force z to be available outside the loop once it's been created:
although, if you're working in global scope, z is now available everywhere, with the value 10.
This behaviour is because we're working in the REPL. It's generally better practice to put your code inside functions, where you don't need to mark variables inherited from outside the loop as global:

#### Fine tuning the loop: Continue

Sometimes on a particular iteration you might want to skip to the next value. You can use continue to skip the rest of the code inside the loop and start the loop again with the next value.

#### Comprehensions

This oddly-named concept is simply a way of generating and collecting items. In mathematical circles you would say something like this:
In Julia, you can write this as:
and the [n for n in 1:10] construction is called array comprehension or list comprehension ('comprehension' in the sense of 'getting everything' rather than 'understanding'). The outer brackets collect together the elements generated by evaluating the expression placed before the for iteration. Instead of end, use a square bracket to finish.
The type of elements can be specified:
But Julia can work out the types of the results you're producing:
Here's how to make a dictionary via comprehension:
Next, here are two iterators in a comprehension, separated with a comma, which makes generating tables very easy. Here we're making a tuple-table:
r goes through five cycles, one cycle for every value of c. Nested loops work in the opposite manner. Here the column-major order is respected, as shown when the array is filled with nanosecond time values:
You can supply a test expression as well to filter the production. For example, produce all the integers between 1 and 100 that are exactly divisible by 7:

##### Generator expressions

Like comprehensions, generator expressions can be used to produce values from iterating a variable, but, unlike comprehensions, the values are produced on demand.

#### Enumerating arrays

Often you want to go through an array element by element while also keeping track of the index number of each element. The enumerate function gives you an iterable version of something, producing both an index number and the value at each index number:
The array is checked for possible changes at each iteration of the loop.

#### Zipping arrays

Sometimes you want to work through two or more arrays at the same time, taking the first element of each array first, then the second, and so on. This is possible using the well-named zip function:
You'd think it would all go wrong if the arrays were different sizes. What if the third array is too big, or too small?
but Julia isn't fooled — any oversupply or undersupply in any one of the arrays is handled gracefully.
This however does not work in case of filling of arrays, in this case dimensions must match:

#### Iterable objects

The "for something in something" construction is the same for everything that you can iterate through: arrays, dictionaries, strings, sets, ranges, and so on. In Julia this is a general principle: there are a number of ways in which you can create an "iterable object", an object that is designed to be used as part of the iteration process that provides the elements one at a time.
The most obvious example we've already met is the range object. It doesn't look much when you type it into the REPL:
But it gives you the numbers when you start iterating through it:
Should you want the numbers from a range (or other iterable object) in an array, you can use collect to collect them up:
You don't have to collect every element of an iterable object, you can just iterate through it. This can be particularly helpful when you have iterable objects created by other Julia functions. For example, permutations creates an iterable object containing all the permutations of an array. You could of course use collect to grab them and make a new array:
but on anything large there are going to hundreds or thousands of permutations. That's the reason why iterator objects don't produce all the values from the iteration at the same time: memory and performance. A range object doesn't take up much room, even if iterating over it might take ages, depending on how big the range is. If you generate all the numbers at once, rather than only producing them when they're needed, they would all have to be stored somewhere until you need them…
Julia provides iterable objects for working with other types of data. For example, when you're working with files, you can treat an open file as an iterable object:

##### Use eachindex

A common pattern when iterating through arrays is to perform some task for each value of i, where i is the index number of each element, not the element:
That is idiomatic Julia code and correct in all cases, and faster in some situations (than the alternative following code). A bad code pattern to do the same, in cases where it works (which isn't always), is:

###### Note for advanced users

For the purposes of this introduction, it's probably OK to assume that arrays and matrices are indexed starting at 1 (it's not for fully generic code, i.e. for introducing in registered packages). However, it's certainly possible to use other indexing bases in Julia — for example, the OffsetArrays.jl package lets you choose any starting index. It's a good idea to read the official documentation at once you start working with more advanced types of array indexing.

#### Even more iterators

There's a Julia package called IterTools.jl that provides some advanced iterator functions.
For example, partition groups the objects in the iterator into easily-handled chunks:
chain works through all the iterators one after the other:
subsets works through all subsets of an object. You can specify a size:

#### Nested loops

If you want to nest one loop inside another, you don't have to duplicate the for and end keywords. Just use a comma:
(The useful @show macro prints out the names of things and their values.)
One difference between the shorter and longer forms of nesting loops is the behaviour of break:
Notice that break breaks out of both inner and outer loops in the shorter form, but only out of the inner loop in the longer form.

#### Optimizing nested loops

With Julia, inner loops should concern rows rather than columns. This is due to how arrays are stored in memory. In this Julia array, for example, cells 1, 2, 3, and 4 are stored next to each other in memory (the 'column-major' format). So moving down the columns from 1 to 2 to 3 is faster than moving along rows, because jumping across from column to column, from 1 to 5 to 9, requires an extra calculation:
The following examples consist of simple loops, but the way the rows and columns are iterated differ. The "bad" version looks along the first row column by column, then moves down to the next row, and so on.
In the "good" version, the two loops are nested properly, so that the inner loop moves down through the rows, following the memory layout of the array:
Another way to increase the speed is to remove the array bounds checking, using the macro @inbounds:
Here's the test function:
and the results show the difference in performance just based on the row/column scanning order. The "no check" version is even faster....

### Making your own iterable objects

It's possible to design your own iterable objects. When you're defining your type, you add a couple of methods to Julia's iterate function. Then you can use something like for .. end loop to work through the components of your object, and these iterate methods are called automatically as necessary.
The following example shows how you can create an iterable object that generates the sequence of strings combining an uppercase letter with a number from 1 to 9. So the first item in our sequence is "A1", followed by "A2", "A3", up to "A9", then "B1", "B2", and so on, finishing at "Z9".
First, we'll define a new type called SN (StringNumber):
Later we'll create an iterable object of this type using something like this:
and the iterator will yield all the strings up to "Z9".
We must now add two methods to the iterate function. This function already exists in Julia (that's why you can iterate over all the basic data objects), so the Base prefix is required: we're adding a new method to the existing iterate function, one which is designed to handle these special objects.
The first method takes no arguments, except for the type, and is for starting the iteration process off.
This returns a tuple: the first value, and the future value of the iterator, which we've calculated (just in case we ever want to start the iterator at a point other than "A1").
The second method of iterate takes two arguments: an iterable object and the current state. It again returns a tuple of two values, the next item and the next state. But first, if there are no more values available, the iterate function should return nothing.
Telling the iterator when it's finished is easy, because as soon as the incoming state contains a "[" we've finished, because the code for "[" (91) is immediately after the code for "Z" (90).
With these two methods added to handle the SN type, it's now possible to iterate through them. It's also useful to add methods for a few other Base functions, such as show and length. The length method works out how many more SN strings are available starting at sn.
The iterator is now ready for use:

### While loops

To repeat some expressions while a condition is true, use the while ... end construction.
If you're working outside a function, you'll need the global declaration of x before you can change its value. Inside a function, you don't need global.
If you want the condition to be tested after the statements, rather than before, producing a "do .. until" form, use the following construction:
Here we're using a Boolean switch rather than an if ... end statement.

#### Template for while loops

Here is a basic template for a while loop that will run the function find_value repeatedly until it returns a value that's no greater than 0.
For example, with small changes this code explores the famous Collatz_conjecture
main(12) takes 9 attempts, whereas main(27) takes 111 attempts.
Using Julia's macros, you can create your own control structures. See Metaprogramming.

### Exceptions

If you want to write code that checks for errors and handles them gracefully, use the try ... catch construction.
With a catch phrase, you can handle problems that occur in your code, possibly allowing the program to continue rather than grind to a halt.
In the next example, our code attempts to change the first character of a string directly (which isn't allowed, because strings in Julia can't be modified in place):
The error function raises an error exception with a given message.

### Do block

Finally, let's look at a do block, which is another syntax form that, like the list comprehension, looks at first sight to be a bit backwards (i.e. it can perhaps be better understood by starting at the end and working towards the beginning).
Remember the find example from earlier?
The anonymous function (x -> isequal(13, x)) is the first argument of find, and it operates on the second. But with a do block, you can lift the function out and put it in between a do ... end block construction:
You just lose the arrow and change the order, putting the find function and its target argument first, then adding the anonymous function's arguments and body after the do.
The idea is that it's easier to write a longer anonymous function on multiple lines at the end of the form, rather than wedged in as the first argument.