summaryrefslogtreecommitdiff
path: root/sources/examples/fors.scala
diff options
context:
space:
mode:
authormichelou <michelou@epfl.ch>2003-12-04 10:33:38 +0000
committermichelou <michelou@epfl.ch>2003-12-04 10:33:38 +0000
commit6dac101d485b111e21dd77ec3eee726a7d93f2db (patch)
treefef336b8657d21725fd2d2de625fdc9fc44ebec7 /sources/examples/fors.scala
parent62747ac61475b1714d3e4d141b913b900a4b756d (diff)
downloadscala-6dac101d485b111e21dd77ec3eee726a7d93f2db.tar.gz
scala-6dac101d485b111e21dd77ec3eee726a7d93f2db.tar.bz2
scala-6dac101d485b111e21dd77ec3eee726a7d93f2db.zip
- adapted to new Scala compiler
Diffstat (limited to 'sources/examples/fors.scala')
-rw-r--r--sources/examples/fors.scala43
1 files changed, 36 insertions, 7 deletions
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));
+ }
+
}