Reading Control flow

Last updated: January 12, 2023

 Table of contents

Conditional statements

if

if <predicate>
    <do if true>
end

(If predicate evaluates to false, do nothing).

Example:

function testsign(x)
    if x >= 0
        println("x is positive")
    end
end

testsign(3)
testsign(0)
testsign(-2)

Predicates can be built with many operators and functions.

Examples of predicates:

occursin("that", "this and that")
4 < 3
a != b
2 in 1:3
3 <= 4 && 4 > 5
3 <= 4 || 4 > 5

if else

if <predicate>
    <do if true>
else
    <do if false>
end

Examples:

function testsign(x)
    if x >= 0
        println("x is positive")
    else
        println("x is negative")
    end
end

testsign(3)
testsign(0)
testsign(-2)
a = 2
b = 2.0

if a == b
      println("It's true")
  else
      println("It's false")
  end

if a === b
      println("It's true")
  else
      println("It's false")
  end

This can be written in a terse format:

<predicate> ? <do if true> : <do if false>

Example:

a === b ? println("It's true") : println("It's false")

if elseif else

if <predicate1>
    <do if predicate1 true>
elseif <predicate2>
    <do if predicate1 false and predicate2 true>
else
    <do if predicate1 and predicate2 false>
end

Example:

function testsign(x)
    if x > 0
        println("x is positive")
    elseif x == 0
        println("x is zero")
    else
        println("x is negative")
    end
end

testsign(3)
testsign(0)
testsign(-2)

Loops

while and for loops follow a syntax similar to that of functions:

for name = ["Paul", "Lucie", "Sophie"]
    println("Hello $name")
end
for i = 1:3, j = 3:5
    println(i + j)
end
i = 0

while i <= 10
    println(i)
    global i += 1
end

Comments & questions