Skip to content

Adding list:takeWhile #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions List.ark
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,30 @@
_output
}))

# @brief Take the first n elements of a list, given a predicate
# @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
# @details The original list is left unmodified.
Expand Down
5 changes: 5 additions & 0 deletions tests/list-tests.ark
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down