From 782442afc8c5a3eeaccceadb35598b8a32666890 Mon Sep 17 00:00:00 2001 From: Kyle Date: Tue, 1 Sep 2015 02:21:07 -0700 Subject: [PATCH] Add partition. --- docs/manual.scr | 5 +++++ kutils.lisp | 27 +++++++++++++++++++++++++++ package.lisp | 1 + 3 files changed, 33 insertions(+) diff --git a/docs/manual.scr b/docs/manual.scr index 46cf899..0c255dc 100644 --- a/docs/manual.scr +++ b/docs/manual.scr @@ -133,6 +133,7 @@ some functions I found useful.) @cl:doc(function take) @cl:doc(function drop) @cl:doc(function partial) +@cl:doc(function partition) ) @end(def) @@ -395,6 +396,9 @@ described in "Miscellaneous utilities" under "Vector-related".) @item(@c(partial) is a function defined in @c(kutils.lisp), described in "Miscellaneous utilities" under "Clojure-inspired functions".) +@item(@c(partition) is a function defined in @c(kutils.lisp), described +in "Miscellaneous utilities" under "Clojure-inspired functions".) + @item(@c(read-file-as-string) is a macro defined in @c(macros.lisp), described in "Macros" under "File macros".) @@ -475,6 +479,7 @@ Alphabetical documentation for all exported symbols. @cl:doc(function new-hash-table) @cl:doc(function new-vector) @cl:doc(function partial) +@cl:doc(function partition) @cl:doc(macro sethash) @cl:doc(function symb) @cl:doc(function take) diff --git a/kutils.lisp b/kutils.lisp index 46a18de..a145eca 100644 --- a/kutils.lisp +++ b/kutils.lisp @@ -144,3 +144,30 @@ effectful code, such as logging." (apply fn args)))) +(defun partition-list (test lst) + (let (match no-match) + (dolist (x lst) + (if (funcall test x) + (push x match) + (push x no-match))) + (vector match no-match))) + +(defun partition-vector (test vec) + (let ((match (new-vector)) + (no-match (new-vector))) + (dotimes (i (length vec)) + (let ((x (aref vec i))) + (if (funcall test x) + (vector-push-extend x match) + (vector-push-extend x no-match)))) + (list match no-match))) + +(defun partition (pred seq) + "Split @c(seq) into a pair of sequences with @c(pred) : the first of +the pair are those elements satisfying @c(pred), and the second are +those that do not satisfy @c(pred)." + (cond + ((listp seq) (partition-list pred seq)) + ((vectorp seq) (partition-vector pred seq)) + (t (error "Values of type ~A cannot be partitioned." + (type-of seq))))) diff --git a/package.lisp b/package.lisp index 0d2043b..2b754a8 100644 --- a/package.lisp +++ b/package.lisp @@ -30,6 +30,7 @@ #:cartprod2 #:empty-or-nil-p #:effector + #:partition ;; kutils-hash-tables.lisp #:enable-hash-table-reader