Last active
August 15, 2018 23:01
-
-
Save paulp/fac614c6de23c10644a7af25f4ef96e4 to your computer and use it in GitHub Desktop.
interesting LazyList evaluation semantics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% mscala -v 2.13.0-M4 | |
Welcome to Scala 2.13.0-M4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_181). | |
Type in expressions for evaluation. Or try :help. | |
scala> val counter = { | |
| var count = 0 | |
| () => { | |
| val res = try "x" + count finally count = count + 1 | |
| try res finally println(res) | |
| } | |
| } | |
counter: () => String = $$Lambda$831/992524208@22048bd6 | |
scala> def f = counter() | |
f: String | |
scala> def mk1(n: Int): LazyList[String] = if (n <= 0) LazyList() else f #:: mk1(n - 1) | |
mk1: (n: Int)LazyList[String] | |
scala> def mk2(n: Int): LazyList[String] = LazyList.fill(n)(f) | |
mk2: (n: Int)LazyList[String] | |
scala> def xs = mk1(5) | |
xs: LazyList[String] | |
scala> def ys = mk2(5) | |
ys: LazyList[String] | |
scala> xs(4) | |
x0 | |
res0: String = x0 | |
scala> ys(4) | |
x1 | |
x2 | |
x3 | |
x4 | |
x5 | |
res1: String = x5 | |
scala> xs.zipWithIndex.apply(4) | |
x6 | |
res2: (String, Int) = (x6,4) | |
scala> xs.zipWithIndex.filter(_ => true).apply(4) | |
x7 | |
x8 | |
x9 | |
x10 | |
x11 | |
res3: (String, Int) = (x11,4) | |
scala> xs.zipWithIndex.map(_ => 0).apply(4) | |
x12 | |
res4: Int = 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
:paste
ablexs(4)
ys(4)
xs.zipWithIndex.apply(4)