From 6dac101d485b111e21dd77ec3eee726a7d93f2db Mon Sep 17 00:00:00 2001 From: michelou Date: Thu, 4 Dec 2003 10:33:38 +0000 Subject: - adapted to new Scala compiler --- sources/examples/fors.scala | 43 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) (limited to 'sources/examples/fors.scala') diff --git a/sources/examples/fors.scala b/sources/examples/fors.scala index 55849f4010..cf22c2830e 100644 --- a/sources/examples/fors.scala +++ b/sources/examples/fors.scala @@ -1,8 +1,8 @@ -module fors { +object fors { - trait Person { - val name: String; - val age: Int; + class Person(_name: String, _age: Int) { + val name = _name; + val age = _age; } def printOlderThan20(xs: Seq[Person]): Iterator[String] = @@ -11,8 +11,13 @@ module fors { def printOlderThan20(xs: Iterator[Person]): Iterator[String] = for (val p <- xs; p.age > 20) yield p.name; + val persons = List( + new Person("John", 40), + new Person("Richard", 68) + ); + def divisors(n: Int): List[Int] = - for (val i <- List.range(1, n); n % i == 0) yield i; + for (val i <- List.range(1, n+1); n % i == 0) yield i; def isPrime(n: Int) = divisors(n).length == 2; @@ -22,7 +27,7 @@ module fors { isPrime(i+j)) yield Pair(i, j); def sum(xs: List[Double]): Double = - (0.0 foldl_: xs) { (x, y) => x + y } + xs.foldLeft(0.0) { (x, y) => x + y } def scalProd(xs: List[Double], ys: List[Double]) = sum(for(val Pair(x, y) <- xs zip ys) yield x * y); @@ -59,5 +64,29 @@ module fors { a1 == a2) yield Pair(a1, a2)); def removeDuplicates[a](xs: List[a]): List[a] = - xs.head :: removeDuplicates(for (val x <- xs.tail; x != xs.head) yield x) + if (xs.isEmpty) + xs + else + xs.head :: removeDuplicates(for (val x <- xs.tail; x != xs.head) yield x); + + def main(args: Array[String]) = { + Console.print("Persons over 20:"); + printOlderThan20(persons) foreach { x => Console.print(" " + x) }; + Console.println; + + Console.println("divisors(34) = " + divisors(34)); + + Console.print("findNums(15) ="); + findNums(15) foreach { x => Console.print(" " + x); }; + Console.println; + + val xs = List(3.5, 5.2); + Console.println("average(" + xs + ") = " + + sum(xs) / xs.length); + + val ys = List(2.0, 1.0); + Console.println("scalProd(" + xs + ", " + ys +") = " + + scalProd(xs, ys)); + } + } -- cgit v1.2.3