Skip to content

6. Decisions

A program often has to choose. if, then and else choose between two values:

fn main()
    age = 15
    dbg if age >= 18 then "adult" else "young"
end

The part after if is a question whose answer is True or False. When it is True you get the value after then; when it is False, the value after else. The questions you can ask about numbers are < (less than), > (greater than), <= and >= (or equal), == (equal) and != (not equal). == has two =, because one = gives a name a value.

To choose between more than two values, use case. Each line under it is a question, ->, and the value to give back when its answer is True. Nomi asks them from the top and takes the first that is True. _ stands for “anything else”, so the last line catches what the questions above it didn’t. end closes the case:

fn size(n: Int) -> String
    case
        n < 10  -> "small"
        n < 100 -> "medium"
        _       -> "large"
    end
end

fn main()
    dbg size(5)
    dbg size(50)
    dbg size(500)
end

if is also how you divide safely. Dividing a whole number by zero has no answer, so when the Int you divide by could be zero, Nomi won’t run your code until you check it. Here share splits some sweets between children, and nothing stops children from being 0:

fn share(sweets: Int, children: Int) -> Int
    sweets / children
end

fn main()
    dbg share(10, 3)
end

The message says / wants a NonZeroInt, a whole number that is never zero. Its help says what to do: check it first.

fn share(sweets: Int, children: Int) -> Int
    if children == 0 then 0 else sweets / children
end

fn main()
    dbg share(10, 3)
    dbg share(10, 0)
end

In the else, children can’t be zero, and Nomi knows it, so the division is allowed there. You choose the answer for when there is no one to share with: here, 0 each. Nomi checks a Decimal you divide by in the same way.

describe gets a temperature in degrees. It should give back "cold" below 10, "hot" from 25 up, and "mild" in between. Right now it knows only cold and mild.

fn describe(temperature: Int) -> String
    if temperature < 10 then "cold" else "mild"
end

// The checks below run when you press Check. You don't need to change them.
test "5 degrees is cold"
    assert describe(5) == "cold"
end

test "18 degrees is mild"
    assert describe(18) == "mild"
end

test "30 degrees is hot"
    assert describe(30) == "hot"
end