Follow up on the Scala Prime Factors Kata

So my fellow OCIer Tim Dalton took up my challenge to find me the “scala way” of implementing the solution in a nice one liner. I changed the example in the spec to allow a result of a list with 1 in it instead of an empty list to get rid of the conditional… the result was tasty. :)

Also goes to show there’s still a lot more for me to learn about scala.

(for (i <- Stream.range(2,n/2); if n % i == 0 ) yield (i)).headOption.map{x => x :: apply(n / x)}.getOrElse(List(n))

He also quickly followed this up with a 2.8 compatible version as well:

object GeneratePrimeFactors extends (Int => List[Int]) {
                override def apply(n:Int) = (for (i <- Stream.range(2,n/2); if n % i == 0 ) yield (i)).headOption.map{x => x :: apply(n / x)}.getOrElse(List(n))
}
You can leave a response, or trackback from your own site.

Facebook comments:

Leave a Reply

Subscribe to RSS Feed Follow me on Twitter!