1. Engineering
  2. Computer Science
  3. this are different exercise you must not use while...

Question: this are different exercise you must not use while...

Question details

this are different EXERCISE

.

You MUST NOT use while loops or (re)assignment to variables (you can use "val" declarations,
* but not "var" declarations). You must use recursion instead.
*
* . You may declare auxiliary functions if you like.
*

*/

object fp1 {

// EXAMPLE: here is the definition of the factorial function.
def fact (n : Int) : Int = {
if (n <= 1)
1
else
n * fact (n - 1)
}

// EXERCISE 5: write a function "swap" that takes a pair of an Int and a String, and returns a
// pair of a String and an Int (with the values from the pair passed an argument. E.g., swap (p1)
// should return ("hello", 7). You can use "p._1" and "p._2" to access the first and second
// components of a pair.
def swap (p:(Int,String)) : (String,Int) = {
// TODO: Provide definition here.
null
}

// EXERCISE 6: write a function "sum" that takes a list of integers and sums them. As with all of
// the exercises in this assignment, your function MUST be recursive and MUST NOT use a while
// loop.
def sum (xs : List[Int]) : Int = {
// TODO: Provide definition here.
-1
}

// EXERCISE 7: given the definition of the function "sumTailRecursiveAux" below, complete the
// definition of the function "sumTailRecursive" so that it also sums a list of integers. You
// must not alter the definition of "sumTailRecursiveAux". Your definition for "sumTailRecursive"
// must call "sumTailRecursiveAux" directly, and must not call "sum"
def sumTailRecursiveAux (accumulator : Int, xs : List[Int]) : Int = {
xs match {
case Nil => accumulator
case y::ys => sumTailRecursiveAux (accumulator + y, ys)
}
}

def sumTailRecursive (xs : List[Int]) : Int = {
// TODO: Provide definition here.
-1
}

// EXERCISE 8: complete the following definition of the function "max" that finds the maximum
// integer in a list of integers. Note that no value can be returned when the list is empty,
// hence the "NoSuchElementException". Your function MUST be recursive and MUST NOT use a while
// loop. You MUST NOT use the "max" method on lists, but can use the "max" method on integers.
def max (xs : List[Int]) : Int = {
// TODO: Provide definition here.
-1
}

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution