diff --git a/exercises/src/main/scala/fpinscala/datastructures/List.scala b/exercises/src/main/scala/fpinscala/datastructures/List.scala index b9b484480b..908c5199ef 100644 --- a/exercises/src/main/scala/fpinscala/datastructures/List.scala +++ b/exercises/src/main/scala/fpinscala/datastructures/List.scala @@ -11,24 +11,24 @@ object List { // `List` companion object. Contains functions for creating and wo def sum(ints: List[Int]): Int = ints match { // A function that uses pattern matching to add up a list of integers case Nil => 0 // The sum of the empty list is 0. case Cons(x,xs) => x + sum(xs) // The sum of a list starting with `x` is `x` plus the sum of the rest of the list. - } - + } + def product(ds: List[Double]): Double = ds match { case Nil => 1.0 case Cons(0.0, _) => 0.0 case Cons(x,xs) => x * product(xs) } - + def apply[A](as: A*): List[A] = // Variadic function syntax if (as.isEmpty) Nil else Cons(as.head, apply(as.tail: _*)) val x = List(1,2,3,4,5) match { case Cons(x, Cons(2, Cons(4, _))) => x - case Nil => 42 + case Nil => 42 case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y case Cons(h, t) => h + sum(t) - case _ => 101 + case _ => 101 } def append[A](a1: List[A], a2: List[A]): List[A] = @@ -42,11 +42,11 @@ object List { // `List` companion object. Contains functions for creating and wo case Nil => z case Cons(x, xs) => f(x, foldRight(xs, z)(f)) } - - def sum2(ns: List[Int]) = + + def sum2(ns: List[Int]) = foldRight(ns, 0)((x,y) => x + y) - - def product2(ns: List[Double]) = + + def product2(ns: List[Double]) = foldRight(ns, 1.0)(_ * _) // `_ * _` is more concise notation for `(x,y) => x * y`; see sidebar @@ -65,4 +65,4 @@ object List { // `List` companion object. Contains functions for creating and wo def foldLeft[A,B](l: List[A], z: B)(f: (B, A) => B): B = sys.error("todo") def map[A,B](l: List[A])(f: A => B): List[B] = sys.error("todo") -} \ No newline at end of file +}