Functions that Yield Boolean Values


Using functions that produce boolean results

A function is not required to produce a number as its answer. It can, for example, produce a boolean answer (true or false). An example of such a function is isOdd(n), which yields true if n is an odd integer. For example, isOdd(3) = true but isOdd(4) = false.

Remember that a question is just an expression that produces a boolean answer. For example, suppose that function jump(n) is defined by two cases as follows.

  case jump(n) = 3*n + 1    when isOdd(n)
  case jump(n) = n `div` 2
Then
  jump(7) 
    = 3*7 + 1             (since isOdd(7) is true)
    = 21 + 1
    = 22
but
  jump(6) 
    = 6 `div` 2           (since isOdd(6) is false)
    = 3


Defining your own functions that produce boolean results

The general rules for creating your own functions that produce boolean values are exactly the same as for other functions. Just make sure that the result is either true or false.

Above we used function isOdd(n). But that function is not already defined for you. You need to create it yourself. But that is not a problem, since n is odd just when the remainder is 1 when you divide n by 2. So here is a short definition of isOdd(n).

  isOdd(n) = n `div` 2 == 1
Let's try computing isOdd(3) and isOdd(4).
  isOdd(3)
    = 3 `div` 2 == 1
    = 1 == 1
    = true
But
  isOdd(4)
    = 4 `div` 2 == 1
    = 0 == 1
    = false

Suppose that we want to say that x and y are close to one another if they are within 1 of each other. So 10 and 11 are close, but 10 and 12 are not. Specifically, x and y are close if |x - y| ≤ 1. Here is a definition of close(x,y) in Cinnameg.

  close(x,y) = absolute(x - y) <= 1
Let's compute close(10,11).
  close(10,11)
    = absolute(10 - 11) <= 1
    = absolute(-1) <= 1
    = 1 <= 1              (since we know that absolute(-1) is 1)
    = true


Problems

  1. [solve] Write a definition of isPositive(x), which yields true if x is a positive number.

  2. [solve] Write a definition of isDivisibleBy(n,m), which yields true if n is divisibly by m. For example, isDivisibleBy(10,5) is true, but isDivisibleBy(10,7) is false.


Summary

A function can produce a boolean result.


Review

There are two boolean values, true and false. An expression can have a boolean value as its value.

You can combine boolean values using operators and and or. Use not to get the opposite of a boolean value.