- 整数生成器
package week2 trait Generator[+T] { def generate: T } object Test extends App { val integers = new Generator[Int] { val random = new java.util.Random() def generate = random.nextInt() } print (integers.generate) }
2.布尔值生成器
val bools = new Generator[Boolean] { def generate = integers.generate > 0 } for (i <- 1 to 10) println (bools.generate)
3. Pair生成器
val pairs = new Generator[(Int, Int)] { def generate = (integers.generate, integers.generate) } for (i <- 1 to 10) println (pairs.generate)
4. 能不能更简洁些,每次都用 new Generator很麻烦
如果能这样岂不很好
val booleans = for (x <- integers) yield x > 0 def pairs[T, U](t: Generator[T], u: Generator[U]) = for { x <- t y <- u } yield (x, y)
通过上节我们知道for循环没翻译成map,flatMat,filter来执行,要想在for循环中用integers就得定义map函数
package week2 trait Generator[+T] { self => def generate: T def map[S](f: T => S):Generator[S] = new Generator[S] { def generate = f(self.generate) } } object Test extends App { val integers = new Generator[Int] { val random = new java.util.Random() def generate = random.nextInt() } val bools = for (x <- integers) yield x > 0 println( bools.generate) }
5. Pair生成器也可以这样生成
时间: 2024-08-26 15:27:19