fork download
  1. def combinations[T](k: Int, list: List[T]) : List[List[T]] = {
  2. | list match {
  3. | case Nil => Nil
  4. | case head :: xs =>
  5. | if (k <= 0 || k > list.length) {
  6. | Nil
  7. | } else if (k == 1) {
  8. | list.map(List(_))
  9. | } else {
  10. | combinations(k-1, xs).map(head :: _) ::: combinations(k, xs)
  11. | }
  12. | }
  13. | }
  14. combinations: [T](Int,List[T])List[List[T]]
  15.  
  16. scala> case class S99Int(val i: Int) {
  17. |
  18. | def isPrime : Boolean = {
  19. | if (i <= 1) false
  20. | else if (i == 2) true
  21. | else !(2 to (i-1)).exists(x => i % x == 0)
  22. | }
  23. |
  24. | def goldbach : Option[List[Int]] = {
  25. | val primes = (3 to i).filter(x => S99Int(x).isPrime).toList
  26. | combinations(2, primes).find(_.foldLeft(0)((a,b) => a+b) == i)
  27. | }
  28. |
  29. | }
  30. defined class S99Int
  31.  
  32. scala> implicit def i2S99(i: Int) : S99Int = new S99Int(i)
  33. i2S99: (Int)S99Int
  34.  
  35. scala> def printGoldbachListLimited(r: Range, lowerBound: Int) = {
  36. | r.foreach(i => i.goldbach match {
  37. | case Some(List(a,b)) if a > lowerBound => println("%d = %d + %d".format(i,a,b))
  38. | case _ =>
  39. | })
  40. | }
  41. printGoldbachListLimited: (Range,Int)Unit
  42.  
  43. scala> def printGoldbachList(r: Range) = {
  44. | printGoldbachListLimited(r, 0)
  45. | }
  46. printGoldbachList: (Range)Unit
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.scala:1: error: expected class or object definition
def combinations[T](k: Int, list: List[T]) : List[List[T]] = {
^
Main.scala:14: error: expected class or object definition
combinations: [T](Int,List[T])List[List[T]]
^
Main.scala:16: error: expected class or object definition
scala> case class S99Int(val i: Int) {
^
Main.scala:30: error: expected class or object definition
defined class S99Int
^
Main.scala:32: error: expected class or object definition
scala> implicit def i2S99(i: Int) : S99Int = new S99Int(i)
^
Main.scala:33: error: expected class or object definition
i2S99: (Int)S99Int
^
Main.scala:35: error: expected class or object definition
scala> def printGoldbachListLimited(r: Range, lowerBound: Int) = {
^
Main.scala:41: error: expected class or object definition
printGoldbachListLimited: (Range,Int)Unit
^
Main.scala:43: error: expected class or object definition
scala> def printGoldbachList(r: Range) = {
^
Main.scala:46: error: expected class or object definition
printGoldbachList: (Range)Unit
^
10 errors found
stdout
Standard output is empty