diff -r f88b5cec2e5d -r 1bde878ba6c9 progs/lecture2.scala --- a/progs/lecture2.scala Sun Nov 15 13:10:43 2020 +0000 +++ b/progs/lecture2.scala Tue Nov 17 00:34:55 2020 +0000 @@ -210,28 +210,34 @@ def odd(x: Int) : Boolean = x % 2 == 1 val lst = (1 to 10).toList -lst.reverse.sorted - lst.filter(even) lst.count(odd) lst.find(even) lst.exists(even) +lst.find(_ < 4) lst.filter(_ < 4) -lst.filter(x => x % 2 == 1) + +def less4(x: Int) : Boolean = x < 4 +lst.find(less4) +lst.find(_ < 4) + +lst.filter(x => x % 2 == 0) lst.filter(_ % 2 == 0) -lst.sortWith((x, y) => x > y) -lst.sortWith(_ < _) +lst.sortWith((x, y) => x < y) +lst.sortWith(_ > _) // but this only works when the arguments are clear, but // not with multiple occurences lst.find(n => odd(n) && n > 2) -val ps = List((3, 0), (3, 2), (4, 2), (2, 2), (2, 0), (1, 1), (1, 0)) + +val ps = List((3, 0), (3, 2), (4, 2), (2, 2), + (2, 0), (1, 1), (1, 0)) def lex(x: (Int, Int), y: (Int, Int)) : Boolean = if (x._1 == y._1) x._2 < y._2 else x._1 < y._1 @@ -251,12 +257,26 @@ def double(x: Int): Int = x + x def square(x: Int): Int = x * x - val lst = (1 to 10).toList +lst.map(square) lst.map(x => (double(x), square(x))) -lst.map(square) +// works also for strings +def tweet(c: Char) = c.toUpper + +"Hello World".map(tweet) + + +// this can be iterated + +lst.map(square).filter(_ > 4) + +(lst.map(square) + .find(_ > 4) + .map(square)) + +lst.map(square).find(_ > 4) // this is actually how for-comprehensions are // defined in Scala @@ -264,20 +284,10 @@ lst.map(n => square(n)) for (n <- lst) yield square(n) -// this can be iterated - -lst.map(square).filter(_ > 4) - -(lst.map(square) - .filter(_ > 4) - .map(square)) - - // lets define our own higher-order functions // type of functions is for example Int => Int - def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = { if (lst == Nil) Nil else f(lst.head) :: my_map_int(lst.tail, f) @@ -290,10 +300,10 @@ // of switch statement on steroids (see more later on) def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = -lst match { - case Nil => Nil - case x::xs => f(x)::my_map_int(xs, f) -} + lst match { + case Nil => Nil + case x::xs => f(x)::my_map_int(xs, f) + } // other function types @@ -693,16 +703,16 @@ /* * 1 - * / | \ - * / | \ - * / | \ - * 2 3 8 - * / \ / \ / \ - * 4 5 6 7 9 10 - * Preorder: 1,2,4,5,3,6,7,8,9,10 - * InOrder: 4,2,5,1,6,3,7,9,8,10 - * PostOrder: 4,5,2,6,7,3,9,10,8,1 - * + * / | \ + * / | \ + * / | \ + * 2 3 8 + * / \ / \ / \ + * 4 5 6 7 9 10 + * Preorder: 1,2,4,5,3,6,7,8,9,10 + * InOrder: 4,2,5,1,6,3,7,9,8,10 + * PostOrder: 4,5,2,6,7,3,9,10,8,1 + * show inorder, preorder, postorder