Skip to content

Commit c89574a

Browse files
committed
more testing and docs
1 parent 555c776 commit c89574a

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/main/scala/scala/collection/immutable/next/package.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ package object next {
1919
* When called on a finite `LazyList`, returns a circular structure
2020
* that endlessly repeats the elements in the input.
2121
* The result is a true cycle occupying only constant memory.
22+
*
23+
* Safe to call on unbounded input, but in that case the result is not a cycle
24+
* (not even if the input was).
2225
*/
2326
def cycle: LazyList[T] =
2427
// case 1: the input is already known to be empty

src/test/scala/scala/collection/immutable/TestLazyListExtensions.scala

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,13 @@ import org.junit.Test
1818
import next._
1919

2020
class TestLazyListExtensions {
21+
22+
// This method will *not* terminate for non-cyclic infinite-sized collections.
23+
def assertIsCyclical[T](xs: LazyList[T]): Unit = {
24+
assertTrue(xs.nonEmpty)
25+
xs.force
26+
}
27+
2128
@Test
2229
def testEmpty1(): Unit = {
2330
val xs = LazyList.empty // realized
@@ -39,6 +46,7 @@ class TestLazyListExtensions {
3946
val xs = LazyList(1, 2, 3)
4047
val cyc = xs.cycle
4148
assertFalse(cyc.isEmpty)
49+
assertIsCyclical(cyc)
4250
assertEquals(LazyList(1, 2, 3, 1, 2, 3, 1, 2), cyc.take(8))
4351
}
4452
@Test
@@ -76,4 +84,32 @@ class TestLazyListExtensions {
7684
assertEquals(10, cyc.take(10).size)
7785
assertEquals(3, counter)
7886
}
87+
@Test
88+
def testConstantMemory3(): Unit = {
89+
val xs = LazyList(1, 2, 3)
90+
val cyc = xs.cycle
91+
assertIsCyclical(cyc)
92+
assertIsCyclical(cyc.tail)
93+
assertIsCyclical(cyc.tail.tail)
94+
assertIsCyclical(cyc.tail.tail.tail)
95+
assertIsCyclical(cyc.tail.tail.tail.tail)
96+
assertIsCyclical(cyc.drop(1))
97+
assertIsCyclical(cyc.drop(10))
98+
}
99+
@Test
100+
def testUnbounded(): Unit = {
101+
val xs = LazyList.from(1)
102+
val cyc = xs.cycle
103+
assertEquals(LazyList(1, 2, 3), cyc.take(3))
104+
}
105+
@Test
106+
def testSecondCallIsSafeButNotIdempotent(): Unit = {
107+
val xs = LazyList(1, 2, 3)
108+
// this is safe to do
109+
val twice = xs.cycle.cycle
110+
// and the contents are as expected
111+
assertEquals(LazyList(1, 2, 3, 1, 2, 3, 1, 2), twice.take(8))
112+
// but the result is not a cycle. TODO do we care?
113+
assertFalse(twice.tail eq twice.tail.tail.tail.tail)
114+
}
79115
}

0 commit comments

Comments
 (0)