Skip to content

Instantly share code, notes, and snippets.

@paulp
Last active August 15, 2018 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulp/fac614c6de23c10644a7af25f4ef96e4 to your computer and use it in GitHub Desktop.
Save paulp/fac614c6de23c10644a7af25f4ef96e4 to your computer and use it in GitHub Desktop.
interesting LazyList evaluation semantics
% 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
@NthPortal
Copy link

NthPortal commented Aug 15, 2018

:pasteable

val counter = {
  var count = 0
  () => {
    val res = try "x" + count finally count = count + 1
    try res finally println(res)
  }
}

def f = counter()

def mk1(n: Int): LazyList[String] = if (n <= 0) LazyList() else f #:: mk1(n - 1)

def mk2(n: Int): LazyList[String] = LazyList.fill(n)(f)

def xs = mk1(5)

def ys = mk2(5)
xs(4)
ys(4)
xs.zipWithIndex.apply(4)
xs.zipWithIndex.filter(_ => true).apply(4)
xs.zipWithIndex.map(_ => 0).apply(4)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment