Skip to content

Commit

Permalink
Add partion-by and take-while
Browse files Browse the repository at this point in the history
  • Loading branch information
eigenhombre committed Jun 5, 2022
1 parent 66415cd commit 2be6a8b
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 1 deletion.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Supported operators:
neg?
partial
partition-all
partition-by
partition-n (called "partition" in Clojure)
pos?
rand-int
Expand All @@ -43,6 +44,7 @@ Supported operators:
sort-by
spit
take
take-while

# Usage

Expand Down
19 changes: 19 additions & 0 deletions src/main.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,22 @@
;; You should just use `remove-if-not`!
(defun filter (f l)
(remove-if-not f l))

(defun take-while (f l)
(loop for x in l
with ret
do (progn
(when (not (funcall f x))
(return (nreverse ret)))
(setq ret (cons x ret)))
finally (return l)))

(defun partition-by (f l)
(when l
(let* ((fst (first l))
(fv (funcall f fst))
(run (cons fst
(take-while (lambda (x)
(equal fv (funcall f x)))
(rest l)))))
(cons run (partition-by f (nthcdr (length run) l))))))
4 changes: 3 additions & 1 deletion src/package.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
:neg?
:partial
:partition-all
:partition-by
:partition-n
:pos?
:rand-int
Expand All @@ -21,4 +22,5 @@
:sort-by
:slurp
:spit
:take))
:take
:take-while))
22 changes: 22 additions & 0 deletions test/main.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,25 @@
(cl-oju:filter (constantly t)
(cl-oju:range 10))))
(is (equal '(1 3 5) (cl-oju:filter #'oddp (cl-oju:range 6)))))

(test take-while
(is (null (cl-oju:take-while #'evenp ())))
(is (equal '(0)
(cl-oju:take-while #'evenp (cl-oju:range 3))))
(let ((f (lambda (x) (< x 3))))
(is (equal '(0 1 2)
(cl-oju:take-while f (cl-oju:range 100))))))

(test partition-by
(is (null (cl-oju:partition-by #'evenp ())))
(is (equal '((0) (1) (2))
(cl-oju:partition-by #'evenp
(cl-oju:range 3))))
(is (equal '((0) (1) (2))
(cl-oju:partition-by #'oddp
(cl-oju:range 3))))
(is (equal '((a a a) (b) (c c c) (b) (a a a))
(cl-oju:partition-by
(lambda (x) (eq 'b x))
'(a a a b c c c b a a a)))))

0 comments on commit 2be6a8b

Please sign in to comment.