diff options
author | Martin Odersky <odersky@gmail.com> | 2003-03-03 14:33:53 +0000 |
---|---|---|
committer | Martin Odersky <odersky@gmail.com> | 2003-03-03 14:33:53 +0000 |
commit | 6749e5dd658522cb63600021a9ee5a86f911cfeb (patch) | |
tree | a22d4bf7f2bf71b5775418dfddaa31a1640313d1 /sources/examples/fors.scala | |
parent | e1fb3fb655a067039870016b3a47e2305d692d98 (diff) | |
download | scala-6749e5dd658522cb63600021a9ee5a86f911cfeb.tar.gz scala-6749e5dd658522cb63600021a9ee5a86f911cfeb.tar.bz2 scala-6749e5dd658522cb63600021a9ee5a86f911cfeb.zip |
*** empty log message ***
Diffstat (limited to 'sources/examples/fors.scala')
-rw-r--r-- | sources/examples/fors.scala | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/sources/examples/fors.scala b/sources/examples/fors.scala new file mode 100644 index 0000000000..55849f4010 --- /dev/null +++ b/sources/examples/fors.scala @@ -0,0 +1,63 @@ +module fors { + + trait Person { + val name: String; + val age: Int; + } + + def printOlderThan20(xs: Seq[Person]): Iterator[String] = + printOlderThan20(xs.elements); + + def printOlderThan20(xs: Iterator[Person]): Iterator[String] = + for (val p <- xs; p.age > 20) yield p.name; + + def divisors(n: Int): List[Int] = + for (val i <- List.range(1, n); n % i == 0) yield i; + + def isPrime(n: Int) = divisors(n).length == 2; + + def findNums(n: Int): Iterator[Pair[Int, Int]] = + for (val i <- Iterator.range(1, n); + val j <- Iterator.range(1, i-1); + isPrime(i+j)) yield Pair(i, j); + + def sum(xs: List[Double]): Double = + (0.0 foldl_: xs) { (x, y) => x + y } + + def scalProd(xs: List[Double], ys: List[Double]) = + sum(for(val Pair(x, y) <- xs zip ys) yield x * y); + + type Lst = List[Any]; + + val books = List( + 'book('title("Structure and Interpretation of Computer Programs"), + 'author("Abelson, Harald"), + 'author("Sussman, Gerald J.")), + 'book('title("Principles of Compiler Design"), + 'author("Aho, Alfred"), + 'author("Ullman, Jeffrey")), + 'book('title("Programming in Modula-2"), + 'author("Wirth, Niklaus"))); + + def findAuthor(books: Lst) = + for (val 'book(book: Lst) <- books; + val 'title(title: String) <- book; + (title indexOf "Program") >= 0; + val 'author(author: String) <- book) yield author; + + for (val 'book(b: Lst) <- books; + val 'author(author: String) <- b; + author startsWith "Ullman"; + val 'title(title: String) <- b) yield title; + + removeDuplicates( + for (val 'book(b1: Lst) <- books; + val 'book(b2: Lst) <- books; + b1 != b2; + val 'author(a1: String) <- b1; + val 'author(a2: String) <- b2; + 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) +} |