--- /dev/null
+
+object Main {
+ // Question 1: HOF on lists.
+ def lengthStrings(l: List[String]) = l map (_ length)
+ def dup[T](e: T, n: Int) = (1 to n) map (_ => e)
+ def dot(l1: List[Int], l2: List[Int]) = (l1 zip l2) map { case (a, b) => a * b }
+
+ // Question 2: Folding functions on lists.
+ def areTrue(l: List[Boolean]) = l reduceLeft (_ && _)
+ def lString(l: List[String]): Int = l.foldLeft(0)((acc, s) => acc + s.length())
+ def longest(l: List[String]): (Int, String) = l.foldLeft(0, ""){ case (curr@(len, longestStr), str) => if (str.length() > len) (str.length(), str) else curr }
+ def isPresent[T](l: List[T], e: T): Boolean = l.foldLeft(false)((acc, e2) => acc || e == e2)
+ def flattenList[T](l: List[T]): List[T] = l.foldRight (List.empty[T]) ((e: T, acc: List[T]) =>
+ e match {
+ case l: List[T] => flattenList(l) ++ acc
+ case _ => e :: acc
+ }
+ )
+
+ def main(args: Array[String]): Unit = {
+ println("Question 1")
+ println(s"a) ${lengthStrings(List("How", "long", "are", "we?"))}")
+ println(s"b) ${dup("foo", 5)}")
+ println(s"c) ${dot(List(1, 2, 3), List(2, 4, 3))}")
+
+ println("Question 2")
+ println("a)")
+ println(s"${areTrue(List(true, true, false))}")
+ println(s"${areTrue(List(true, true, true))}")
+ println("b)")
+ println(s"${lString(List("Folding", "is", "fun"))}")
+ println("c)")
+ println(s"${longest(List("What", "is", "the", "longest?"))}")
+ println("d)")
+ println(s"${isPresent(List(1, 2, 3, 4), 5)}")
+ println(s"${isPresent(List(1, 2, 3, 4), 3)}")
+ println("e)")
+ val l = List(List(1, 1), 2, List(3, List(5, 8)));
+ println(s"flattenList($l): ${flattenList(l)}")
+ }
+}