/ * This approach defines mapList in terms of another useful method called tails. Like Daniel, I will put him in an implicit list extension, but this is purely a matter of taste * /
implicit def richerList[A](list : List[A]) = new {
/ * Here, a method called the tail is called that returns every possible tail in the list. This tail is recursive, so it will not explode on large lists. Note that it is slightly different from the Haskell function with the same name. The Haskell version always adds an empty list to the result * /
def tails : List[List[A]] = { def loop(ls : List[A], accum : List[List[A]]) : List[List[A]] = ls match { case _ :: tail => loop(tail, ls :: accum) case _ => accum } loop(list, Nil).reverse }
/ * This is what using tails looks like
scala> "abc".toList.tails res0: List[List[Char]] = List(List(a, b, c), List(b, c), List(c))
* /
/ * Now we can define a mapList based on tails * /
def mapList[B](f : List[A] => B) = tails map f }
/ * And this is what using mapList looks like
scala> "abc".toList mapList (_.reverse.mkString) res1: List[String] = List(cba, cb, c)
* /
James ry
source share