Skip to content

Commit 59e626c

Browse files
committed
Improve laziness and fix tests
1 parent d87d931 commit 59e626c

File tree

3 files changed

+25
-37
lines changed

3 files changed

+25
-37
lines changed

src/main/scala/collection/immutable/LazyListExtensions.scala

Lines changed: 0 additions & 32 deletions
This file was deleted.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package scala.collection.immutable
2+
3+
object LazyListExtensions {
4+
5+
implicit class LazyListCycle[T](ll: LazyList[T]) {
6+
/**
7+
* When called on a finite `LazyList`, returns a circular structure
8+
* that endlessly repeats the elements in the input.
9+
* The result is a true cycle occupying only constant memory.
10+
*/
11+
def cycle: LazyList[T] =
12+
if (ll.knownSize == 0) LazyList.empty
13+
else LazyList.empty #::: {
14+
if (ll.isEmpty) LazyList.empty
15+
else {
16+
lazy val result: LazyList[T] = ll #::: result
17+
result
18+
}
19+
}
20+
}
21+
22+
}

src/test/scala/collection/immutable/TestLazyListExtensions.scala renamed to src/main/scala/scala/collection/immutable/TestLazyListExtensions.scala

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,18 +63,16 @@ class TestLazyListExtensions {
6363
val xs = LazyList(1, 2, 3)
6464
val cyc = xs.cycle
6565
assertTrue(cyc.tail eq cyc.tail.tail.tail.tail)
66-
assertTrue(cyc.tail eq cyc.drop(4)) // TODO: fails
67-
assertTrue(cyc eq cyc.tail.tail.tail) // TODO: fails
68-
assertTrue(cyc eq cyc.drop(3)) // TODO: fails
69-
assertTrue(cyc eq cyc.drop(3)) // TODO: fails
66+
assertTrue(cyc.tail.tail eq cyc.drop(4).tail)
67+
assertTrue(cyc.tail eq cyc.drop(3).tail)
7068
}
7169
@Test
7270
def testConstantMemory2(): Unit = {
7371
var counter = 0
7472
def count(): Int = { counter += 1; counter }
7573
val xs = count() #:: count() #:: count() #:: LazyList.empty
7674
val cyc = xs.cycle
77-
assertEquals(1, counter)
75+
assertEquals(0, counter)
7876
assertEquals(10, cyc.take(10).size)
7977
assertEquals(3, counter)
8078
}

0 commit comments

Comments
 (0)