From f780322bb6a546c2f13bcacb6ca21eb92b6e2fe5 Mon Sep 17 00:00:00 2001 From: Matus Goljer Date: Sat, 3 May 2014 17:22:03 +0200 Subject: [PATCH] Add `-flatten-n` --- README.md | 11 +++++++++++ dash.el | 4 ++++ dev/examples.el | 8 ++++++++ 3 files changed, 23 insertions(+) diff --git a/README.md b/README.md index 092aa55..4b55241 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ Include this in your emacs settings to get syntax highlighting: * [-map-when](#-map-when-pred-rep-list) `(pred rep list)` * [-map-indexed](#-map-indexed-fn-list) `(fn list)` * [-flatten](#-flatten-l) `(l)` +* [-flatten-n](#-flatten-n-num-list) `(num list)` * [-concat](#-concat-rest-lists) `(&rest lists)` * [-mapcat](#-mapcat-fn-list) `(fn list)` * [-slice](#-slice-list-from-optional-to) `(list from &optional to)` @@ -301,6 +302,16 @@ Takes a nested list `l` and returns its contents as a single, flat list. (-flatten '(1 2 (3 . 4))) ;; => '(1 2 (3 . 4)) ``` +#### -flatten-n `(num list)` + +Flatten `num` levels of a nested `list`. + +```cl +(-flatten-n 1 '((1 2) ((3 4) ((5 6))))) ;; => '(1 2 (3 4) ((5 6))) +(-flatten-n 2 '((1 2) ((3 4) ((5 6))))) ;; => '(1 2 3 4 (5 6)) +(-flatten-n 3 '((1 2) ((3 4) ((5 6))))) ;; => '(1 2 3 4 5 6) +``` + #### -concat `(&rest lists)` Returns a new list with the concatenation of the elements in the supplied `lists`. diff --git a/dash.el b/dash.el index 2e2eccf..a411e60 100644 --- a/dash.el +++ b/dash.el @@ -275,6 +275,10 @@ through the REP function." (-mapcat '-flatten l) (list l))) +(defun -flatten-n (num list) + "Flatten NUM levels of a nested LIST." + (-last-item (--iterate (--mapcat (-list it) it) list (1+ num)))) + (defun -concat (&rest lists) "Returns a new list with the concatenation of the elements in the supplied LISTS." (apply 'append lists)) diff --git a/dev/examples.el b/dev/examples.el index 9520f44..ef9c3b8 100644 --- a/dev/examples.el +++ b/dev/examples.el @@ -48,6 +48,14 @@ (-flatten '((1 (2 3) (((4 (5))))))) => '(1 2 3 4 5) (-flatten '(1 2 (3 . 4))) => '(1 2 (3 . 4))) + (defexamples -flatten-n + (-flatten-n 1 '((1 2) ((3 4) ((5 6))))) => '(1 2 (3 4) ((5 6))) + (-flatten-n 2 '((1 2) ((3 4) ((5 6))))) => '(1 2 3 4 (5 6)) + (-flatten-n 3 '((1 2) ((3 4) ((5 6))))) => '(1 2 3 4 5 6) + (-flatten-n 0 '(3 4)) => '(3 4) + (-flatten-n 0 '((1 2) (3 4))) => '((1 2) (3 4)) + (-flatten-n 0 '(((1 2) (3 4)))) => '(((1 2) (3 4)))) + (defexamples -concat (-concat '(1)) => '(1) (-concat '(1) '(2)) => '(1 2)