In the following problems do not use any mutable variables (i.e., variables decl
ID: 3888141 • Letter: I
Question
In the following problems do not use any mutable variables (i.e., variables declared with var) or any mutable predened types such as arrays, mutable sets, and so on. You may dene methods recursively this time. Do not use the if operator in Problems 1-4 below.
4. Write a Scala method squareAll (l: List[Int]):List[Int] which, given an integer list l, squares every element in it, that is, returns a new list containing (in the same order) the square of each element of l. For instance, squareAll(List(1,2,-3,0)) is List(1,4,9,0).
Explanation / Answer
Please find my implementation.
object Main {
def squareAll (l: List[Int]):List[Int] = {
l.map(x => x*x)
}
def main(args: Array[String]): Unit = {
println(squareAll(List(1,2,-3,0)))
}
}
/*
Sample run:
List(1, 4, 9, 0)
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.