a6886bc5d72e0f1b868ecf9f24cffd2e0b106edb
[Scala.git] / Assignment_05 / src / main / scala / Main.scala
1
2 object Main {
3 // Question 1: HOF on lists.
4 def lengthStrings(l: List[String]) = l map (_ length)
5 def dup[T](e: T, n: Int) = (1 to n) map (_ => e)
6 def dot(l1: List[Int], l2: List[Int]) = (l1 zip l2) map { case (a, b) => a * b }
7
8 // Question 2: Folding functions on lists.
9 def areTrue(l: List[Boolean]) = l reduceLeft (_ && _)
10 def lString(l: List[String]): Int = l.foldLeft(0)((acc, s) => acc + s.length())
11 def longest(l: List[String]): (Int, String) = l.foldLeft(0, ""){ case (curr@(len, longestStr), str) => if (str.length() > len) (str.length(), str) else curr }
12 def isPresent[T](l: List[T], e: T): Boolean = l.foldLeft(false)((acc, e2) => acc || e == e2)
13 def flattenList[T](l: List[T]): List[T] = l.foldRight (List.empty[T]) ((e: T, acc: List[T]) =>
14 e match {
15 case l: List[T] => flattenList(l) ++ acc
16 case _ => e :: acc
17 }
18 )
19
20 def main(args: Array[String]): Unit = {
21 println("Question 1")
22 println(s"a) ${lengthStrings(List("How", "long", "are", "we?"))}")
23 println(s"b) ${dup("foo", 5)}")
24 println(s"c) ${dot(List(1, 2, 3), List(2, 4, 3))}")
25
26 println("Question 2")
27 println("a)")
28 println(s"${areTrue(List(true, true, false))}")
29 println(s"${areTrue(List(true, true, true))}")
30 println("b)")
31 println(s"${lString(List("Folding", "is", "fun"))}")
32 println("c)")
33 println(s"${longest(List("What", "is", "the", "longest?"))}")
34 println("d)")
35 println(s"${isPresent(List(1, 2, 3, 4), 5)}")
36 println(s"${isPresent(List(1, 2, 3, 4), 3)}")
37 println("e)")
38 val l = List(List(1, 1), 2, List(3, List(5, 8)));
39 println(s"flattenList($l): ${flattenList(l)}")
40 }
41 }