Created
May 11, 2018 01:01
-
-
Save xuwei-k/14f01de8ca9b64cc4b9228991690b704 to your computer and use it in GitHub Desktop.
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
Welcome to Scala 2.13.0-M4-pre-20d3c21 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_172). | |
Type in expressions for evaluation. Or try :help. | |
scala> class CallByNeed[A](a: => A){ lazy val value: A = a } | |
defined class CallByNeed | |
scala> def unfoldLazyList[A, S](init: S)(f: S => Option[(CallByNeed[A], S)]): LazyList[A] = { | |
| def loop(s: S): LazyList[A] = { | |
| f(s).fold(LazyList.empty[A]){ case (h, t) => | |
| new LazyList.Cons(h.value, loop(t)) | |
| } | |
| } | |
| loop(init) | |
| } | |
unfoldLazyList: [A, S](init: S)(f: S => Option[(CallByNeed[A], S)])LazyList[A] | |
scala> val xs = unfoldLazyList(0){ s => | |
| if (s <= 10) | |
| Some((new CallByNeed({println(s); s.toString}), s + 1)) | |
| else | |
| None | |
| } | |
xs: LazyList[String] = LazyList(_, ?) | |
scala> xs.size | |
res0: Int = 11 | |
scala> xs(8) | |
8 | |
res1: String = 8 | |
scala> xs(3) | |
3 | |
res2: String = 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment