diff --git a/List.ark b/List.ark index 47204be..120fca1 100644 --- a/List.ark +++ b/List.ark @@ -245,6 +245,33 @@ _output })) +### +# @meta List +# @brief Take the first n elements of +# @param _L the list to work on +# @param _f the predicate +# @details The original list is left unmodified. +# =begin +# (print (takeWhile [1 2 3 4 5 6 7 8 9 10] (fun (a) (< a 4)))) # [1 2 3] +# =end +# @author https://github.com/rakista112 +## +(let list:takeWhile (fun (_L _f) { + (mut _index 0) + (mut _output []) + (mut continue true) + (while (and (< _index (len _L)) continue) + (if (_f (@ _L _index)) + { + (set _output (append _output (@ _L _index))) + (set _index (+ 1 _index)) + } + (set continue false) + ) + ) + _output +})) + ### # @brief Unzip a list of [[a b] [c d]...] into [[a c ...] [b d ...]] # @param _L the list to work on diff --git a/tests/list-tests.ark b/tests/list-tests.ark index f73fb59..863049c 100644 --- a/tests/list-tests.ark +++ b/tests/list-tests.ark @@ -51,6 +51,11 @@ (set tests (assert-eq (list:take a 1) [1] "take" tests)) (set tests (assert-eq (list:take a 100) a "take" tests)) + (set tests (assert-eq (list:takeWhile a (fun (c) (< c 0))) [] "takeWhile" tests)) + (set tests (assert-eq (list:takeWhile a (fun (c) (< c 2))) [1] "takeWhile" tests)) + (set tests (assert-eq (list:takeWhile a (fun (c) (< c 3))) [1 2] "takeWhile" tests)) + (set tests (assert-eq (list:takeWhile a (fun (c) (< c 5))) [1 2 3] "takeWhile" tests)) + (set tests (assert-eq (list:unzip zipped) [[1 2 3 4] [5 6 7 8]] "unzip" tests)) (set tests (assert-eq (list:unzip []) [[] []] "unzip" tests))