Question
this are different EXERCISE . You MUST NOT use while loops or (re)assignment to variables (you can use val declarations, * but not var declarations).
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 }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started