Suppose you are implementing a relational employee database, where the database is a list of tuples formed by the names, the phone numbers and the salaries of the employees. For example, a sample database may consist of the following list of tuples:
Note that I have written parentheses around the tuples to make them more readable, but the precedences of different operators in OCaml make this unnecessary.
Define a function
that takes as input a list representing the database and the name of an employee and returns his/her corresponding salary. Think also of some graceful way to deal with the situation where the database does not contain an entry for that particular name, explain it, and implement this in your code.
Define a function
that is like find_salary, except that it returns the phone number instead.
Important: You must again adhere strictly to the given names and the types for the functions.
val db = (\"John\", \"x3456\", 50.1) :: (\"Jane\", \"x1234\", 107.3) :: (\"Joan\", \"unlisted\", 12.7) :: Nil type listOfTuples = List[(String, String, Double)] def find_salary(name: String) = { def search(t: listOfTuples): Double = t match { case (name_, _, salary) :: t if name == name_ => salary case _ :: t => search(t) case Nil => throw new Exception(\"Invalid Argument in find_salary\") } search(db) } def select(pred: (String, String, Double) => Boolean) = { def search(found: listOfTuples): listOfTuples = found match { case (p1, p2, p3) :: t if pred(p1, p2, p3) => (p1, p2, p3) :: search(t) case (p1, p2, p3) :: t if !pred(p1, p2, p3) => search(t) case Nil => Nil case _ => throw new Exception(\"Invalid Argument in select function\") } search(db) } println(\"Searching the salary of \'Joan\' at db: \" + find_salary(\"Joan\")) println(\"\") val predicate = (_:String, _:String, salary:Double) => (salary < 100.0) println(\"All employees that match with predicate \'salary < 100.0\': \") println(\"\\t\" + select(predicate) + \"\ \")