Question | Click to View Answer |
What does the following code print? var stringNums = List("4", "10", "13")
println {
stringNums.map( (n: String) => n.toInt )
}
|
The |
Cube every element in the following list. var goats = List(23, 99)
|
The var goats = List(23, 99)
println {
goats.map { (num) =>
scala.math.pow(num, 3)
}
}
|
What does the following code print? var odds = List(1, 5, 7)
println {
odds.foldLeft(0) { (memo: Int, num: Int) =>
memo + num
}
}
|
The |
Find the longest string in the following array. var names = List("tuco", "jesse", "hank", "gustavo")
|
The println {
names.reduceLeft { (s1: String, s2: String) =>
if (s1.length > s2.length) s1 else s2
}
}
The loop starts by comparing tuco with jesse. jesse is longer, so jesse is compared with the next element, hank. jesse is still longer, so jesse is compared with gustavo. gustavo is longer than jesse and there are no more elements in the list, so gustavo is returned. |
Concatenate the strings in the following list using the var letters = List("g", "o", "a", "t")
|
The println {
letters.foldLeft("") { (memo: String, letter: String) =>
memo + letter
}
}
|
Loop through the following list from right to left and concatenate all of the letters. The answer should be var huh = List("l", "o", "o", "c")
|
The println {
huh.foldRight("") { (letter: String, memo: String) =>
memo + letter
}
}
|
Use the var countries = List("brazil", "argentina", "colombia")
|
The println {
countries.reduceLeft[String] { (c1: String, c2: String) =>
s"$c1, $c2"
}
}
|
Return an array that uppercases all of the letters in the following list. var me = List("i", "am", "quiet")
|
The println {
me.map { (word: String) =>
word.toUpperCase
}
}
|
Sum all of the even numbers in the following list. var whatever = List(1, 2, 3, 4, 5, 6, 7)
|
The println {
whatever.foldLeft(0) { (memo: Int, num: Int) =>
if (num % 2 == 0) memo + num else memo
}
}
|
Concatenate all the words in the following list that start with the letter "b". Seperate each word with a space. var rrr = List("ant", "beer", "battered", "cool", "burger")
|
rrr.filter { (w: String) =>
w.take(1) == "b"
}.reduceLeft { (a: String, b: String) =>
s"$a $b"
}
|