Skip to content

Commit 4320e30

Browse files
authored
Merge pull request #31 from ArkScript-lang/dev
Adding list:takeWhile
2 parents 6bb54cc + 061a40e commit 4320e30

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

List.ark

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,30 @@
221221
_output
222222
}))
223223

224+
# @brief Take the first n elements of a list, given a predicate
225+
# @param _L the list to work on
226+
# @param _f the predicate
227+
# @details The original list is left unmodified.
228+
# =begin
229+
# (print (takeWhile [1 2 3 4 5 6 7 8 9 10] (fun (a) (< a 4)))) # [1 2 3]
230+
# =end
231+
# @author https://github.com/rakista112
232+
(let list:takeWhile (fun (_L _f) {
233+
(mut _index 0)
234+
(mut _output [])
235+
(mut continue true)
236+
(while (and (< _index (len _L)) continue)
237+
(if (_f (@ _L _index))
238+
{
239+
(set _output (append _output (@ _L _index)))
240+
(set _index (+ 1 _index))
241+
}
242+
(set continue false)
243+
)
244+
)
245+
_output
246+
}))
247+
224248
# @brief Unzip a list of [[a b] [c d]...] into [[a c ...] [b d ...]]
225249
# @param _L the list to work on
226250
# @details The original list is left unmodified.

tests/list-tests.ark

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@
5151
(set tests (assert-eq (list:take a 1) [1] "take" tests))
5252
(set tests (assert-eq (list:take a 100) a "take" tests))
5353

54+
(set tests (assert-eq (list:takeWhile a (fun (c) (< c 0))) [] "takeWhile" tests))
55+
(set tests (assert-eq (list:takeWhile a (fun (c) (< c 2))) [1] "takeWhile" tests))
56+
(set tests (assert-eq (list:takeWhile a (fun (c) (< c 3))) [1 2] "takeWhile" tests))
57+
(set tests (assert-eq (list:takeWhile a (fun (c) (< c 5))) [1 2 3] "takeWhile" tests))
58+
5459
(set tests (assert-eq (list:unzip zipped) [[1 2 3 4] [5 6 7 8]] "unzip" tests))
5560
(set tests (assert-eq (list:unzip []) [[] []] "unzip" tests))
5661

0 commit comments

Comments
 (0)