For these problems try to restrict yourself to only using Scala's if-else and match-case expressions. Avoid using Boolean functions (&&, ||, !, ^), the return command, and definitions of additional functions (but != is ok).
To help you get started, here's a stub of numerology.scala.
In numerology a number (i.e., an integer) belongs to one of several kingdoms. If it is an even integer bigger than 10, it belongs to kingdom 1, unless it is also divisible by 100, then it belongs to kingdom 2. Any number less than or equal to 10 belongs to the third kingdom. Otherwise, it is condemned to the lowly fourth kingdom.
Implement a kingdom function:
def kingdom(n: Int): Int = ???
In numerology a positive integer belongs to one of several orders. (Non-positive integers are considered to belong to order 0.) Otherwise the order is computed using the following sacred formula:
family(n) * ilk(n) + genus(n)
· The family of n is 1 if n is a multiple of 3, otherwise it's 2.
· The ilk of 50 is 3, the ilk of all other numbers is 4.
· The genus of a number is 5 if it is a multiple of 7, otherwise it's 6.
Implement an order function:
def order(n: Int): Int = ???
In numerology the species of a number is 1 if it is positive and even, otherwise it's 2. Say what's wrong with the following implementation and fix it:
def species(n: Int) =
if (0 < n) if (n % 2 == 0) 1 else 2
In numerology a positive integer belongs to one of 3 realms. All odd positive numbers belong to realm 1. Even positives not divisible by 3 belong to realm 2. Positive multiples of both 6 and 7 belong to realm 3. All other numbers belong to realm 0.
Implement the following functions
def realm1(n: Int): Int // = 1 if n belongs to realm 1, throws an exception otherwise
def realm2(n: Int): Int // = 2 if n belongs to realm 2, throws an exception otherwise
def realm3(n: Int): Int // = 3 if n belongs to realm 3, throws an exception otherwise
def realm(n: Int): Int // = the realm of n
Notice that the declarations of the types of the realm functions are lies. They all promise that if the user inputs an Int she'll get an Int back. But that's not true. Sometimes they throw exceptions that must be caught. Rewrite the realm 1, 2, and 3 functions so they return Option[Int]. In this case they should return None instead of throwing an exception. The realm function should use a match/case expression to process the optional values and should return an Int. Rename your functions realm1Opt, realm2Opt, realm3Opt, realmOpt so they won't conflict with problem 4.