From f257fb907ecea0ca79df7c8599cfb5df0c30dff9 Mon Sep 17 00:00:00 2001 From: Magnar Sveen Date: Thu, 19 Jun 2014 07:08:15 +0200 Subject: [PATCH] Add -butlast --- README.md | 11 +++++++++++ dash.el | 9 +++++++++ dev/examples.el | 6 ++++++ 3 files changed, 26 insertions(+) diff --git a/README.md b/README.md index 5f0f46a..e8f7390 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ Other list functions not fit to be classified elsewhere. * [-last](#-last-pred-list) `(pred list)` * [-first-item](#-first-item-list) `(list)` * [-last-item](#-last-item-list) `(list)` +* [-butlast](#-butlast-list) `(list)` * [-sort](#-sort-comparator-list) `(comparator list)` * [-list](#-list-rest-args) `(&rest args)` @@ -1410,6 +1411,16 @@ Return the last item of `list`, or nil on an empty list. (-last-item nil) ;; => nil ``` +#### -butlast `(list)` + +Return a list of all items in list except for the last. + +```cl +(-butlast '(1 2 3)) ;; => '(1 2) +(-butlast '(1 2)) ;; => '(1) +(-butlast '(1)) ;; => nil +``` + #### -sort `(comparator list)` Sort `list`, stably, comparing elements using `comparator`. diff --git a/dash.el b/dash.el index 22f977b..8928009 100644 --- a/dash.el +++ b/dash.el @@ -399,6 +399,14 @@ Alias: `-find'" "Return the last item of LIST, or nil on an empty list." (car (last list))) +(defun -butlast (list) + "Return a list of all items in list except for the last." + (let (result) + (while (cdr list) + (!cons (car list) result) + (!cdr list)) + (nreverse result))) + (defmacro --count (pred list) "Anaphoric form of `-count'." (declare (debug (form form))) @@ -1561,6 +1569,7 @@ structure such as plist or alist." "--last" "-first-item" "-last-item" + "-butlast" "-count" "--count" "-any?" diff --git a/dev/examples.el b/dev/examples.el index 945cfac..26ed0e4 100644 --- a/dev/examples.el +++ b/dev/examples.el @@ -549,6 +549,12 @@ new list." (-last-item '(1 2 3)) => 3 (-last-item nil) => nil) + (defexamples -butlast + (-butlast '(1 2 3)) => '(1 2) + (-butlast '(1 2)) => '(1) + (-butlast '(1)) => nil + (-butlast nil) => nil) + (defexamples -sort (-sort '< '(3 1 2)) => '(1 2 3) (-sort '> '(3 1 2)) => '(3 2 1)