Skip to content

Commit

Permalink
Make LazyList.cons.apply lazier
Browse files Browse the repository at this point in the history
Port of scala/scala#9095.

Co-authored-by: NthPortal <nthportal@gmail.com>
  • Loading branch information
ijuma and NthPortal committed Jul 5, 2020
1 parent 5d5c516 commit c90f543
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
Expand Up @@ -1264,7 +1264,7 @@ object LazyList extends SeqFactory[LazyList] {
* @param hd The first element of the result lazy list
* @param tl The remaining elements of the result lazy list
*/
def apply[A](hd: => A, tl: => LazyList[A]): LazyList[A] = newLL(sCons(hd, tl))
def apply[A](hd: => A, tl: => LazyList[A]): LazyList[A] = newLL(sCons(hd, newLL(tl.state)))

/** Maps a lazy list to its head and tail */
def unapply[A](xs: LazyList[A]): Option[(A, LazyList[A])] = #::.unapply(xs)
Expand Down
Expand Up @@ -715,6 +715,20 @@ class LazyListLazinessTest {
// assertLazyAllSkipping(op, 4)
// }

private def genericCons_unapply_properlyLazy(unapply: LazyList[Int] => Option[(Int, LazyList[Int])]): Unit = {
assertLazyAllSkipping(unapply, 1)
}

@Test
def cons_unapply_properlyLazy(): Unit = {
genericCons_unapply_properlyLazy(LazyList.cons.unapply)
}

@Test
def `#::_unapply_properlyLazy`(): Unit = {
genericCons_unapply_properlyLazy(LazyList.#::.unapply)
}

/* factory laziness tests */

@Test
Expand Down Expand Up @@ -776,14 +790,12 @@ class LazyListLazinessTest {
assertRepeatedlyLazy(factory)
}

@Test
def `#:: properlyLazy`(): Unit = {
private def genericCons_properlyLazy(cons: (=> Int, => LazyList[Int]) => LazyList[Int]): Unit = {
val headInitFactory = lazyListFactory { init =>
def gen(index: Int): LazyList[Int] = {
def elem(): Int = { init.evaluate(index); index }
if (index >= LazinessChecker.count) LazyList.empty
// else elem() #:: gen(index + 1)
else gen(index + 1).#::(elem())
else cons(elem(), gen(index + 1))
}

gen(0)
Expand All @@ -795,7 +807,7 @@ class LazyListLazinessTest {
if (index >= LazinessChecker.count) LazyList.empty
else {
init.evaluate(index)
index #:: gen(index + 1)
cons(index, gen(index + 1))
}
}

Expand All @@ -804,6 +816,16 @@ class LazyListLazinessTest {
assertRepeatedlyLazy(tailInitFactory)
}

@Test
def cons_properlyLazy(): Unit = {
genericCons_properlyLazy(LazyList.cons(_, _))
}

@Test
def `#::_properlyLazy`(): Unit = {
genericCons_properlyLazy(_ #:: _)
}

@Test
def `#::: properlyLazy`(): Unit = {
val headInitFactory = lazyListFactory { init =>
Expand Down

0 comments on commit c90f543

Please sign in to comment.