Skip to content

7. True and false

A question such as age >= 18 gives back a Bool: True or False. Three words build bigger questions from smaller ones:

  • a and b is True only when both are.
  • a or b is True when either one is, or both.
  • not a turns True into False, and False into True.

A cinema gives a discount to children under 12 and to people 65 or older:

fn has_discount(age: Int) -> Bool
    age < 12 or age >= 65
end

fn main()
    dbg has_discount(8)
    dbg has_discount(30)
    dbg has_discount(70)
    dbg not has_discount(30)
end

A function that answers a yes-or-no question gives back a Bool, and its name often reads as the question: has_discount, is_empty. Its answer can go straight into an if: if has_discount(age) then 5 else 8.

A roller coaster lets you ride when you are at least 8 years old and at least 120 cm tall. can_ride should answer whether someone can. Right now it lets anyone of that age ride, whatever their height.

fn can_ride(age: Int, height: Int) -> Bool
    age >= 8 and height > 0
end

// The checks below run when you press Check. You don't need to change them.
test "old enough and tall enough"
    assert can_ride(10, 130)
end

test "old enough, but too short"
    assert not can_ride(10, 110)
end

test "tall enough, but too young"
    assert not can_ride(6, 130)
end