From 61c0afb9abb9ab27a9a881e58dae178a8ce50710 Mon Sep 17 00:00:00 2001 From: Jonas Wanke Date: Wed, 11 Dec 2024 20:56:52 +0100 Subject: [PATCH] =?UTF-8?q?Add=20list.windows(=E2=80=A6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages_v5/example.candy | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/packages_v5/example.candy b/packages_v5/example.candy index 3696367ce..2e6508e9c 100644 --- a/packages_v5/example.candy +++ b/packages_v5/example.candy @@ -415,6 +415,25 @@ fun map[T, R](list: List[T], transform: (T) R) List[R] { result.append(transform(item)) }) } +fun windows[T](list: List[T], windowLength: Int) List[List[T]] { + # Returns a list over all contiguous windows of length `windowLength`. + # + # The windows overlap. If the `list` is shorter than `windowLength`, the + # resulting list is empty. + needs(windowLength.isPositive()) + + list.windowsHelper(windowLength, listOf[List[T]]()) +} +fun windowsHelper[T](list: List[T], windowLength: Int, resultSoFar: List[List[T]]) List[List[T]] { + let index = resultSoFar.length() + switch index.isLessThanOrEqualTo(list.length().subtract(windowLength)) { + true => list.windowsHelper( + windowLength, + resultSoFar.append(list.getRange(index, index.add(windowLength))), + ), + false => resultSoFar, + } +} impl[T: ToText] List[T]: ToText { fun toText(self: List[T]) Text { let items = self.map((item: T) { item.toText() })