Step 8: Conjectural calculation

Here we get to the heart of our collatz function:

n := (if n % 2 == 0 { n / 2 } else { n * 3 + 1 })

It combines multiple elements that we’ve looked at separately. At the top level, it is an assignment expression: it assigns a new value to n. What value? The value of a conditional, that is, of an if.

But wait! This if has a new element. Let’s look at The sharp-eyed reader will have noticed that the if was in parentheses; this is required by Ursa’s grammar in order to avoid ambiguity. Parentheses are often useful to remove ambiguity, either, as here, for the computer, or for the human reader. expression:

if n % 2 == 0 { n / 2 } else { n * 3 + 1 }

The condition of the if is n % 2 == 0. The percent is a shorthand for “remainder after division by”. So we are testing whether the remainder after dividing n by 2 is 0; that is, whether n is even.

So if n is even, the value of the if expression is n / 2. The forward slash / means division.

What if n is odd? This is where else comes in: if the condition of the if is false, we evaluate the What if there is no else? Good question! We’ll come back to it. body. In this case, it is n * 3 + 1, that is, 3 times n plus 1.

So, we assign n to be half of itself if it’s even, or three times itself plus 1 if it’s odd. Does that sound familiar? It’s the steps of the Collatz conjecture!

What have we calculated?