From ed4781435be1222424c6a364ac12a3fa8813bf9b Mon Sep 17 00:00:00 2001 From: Magnar Sveen Date: Tue, 23 Oct 2012 08:58:24 +0200 Subject: [PATCH] Add -dotimes --- README.md | 10 ++++++++++ dash.el | 11 +++++++++++ examples.el | 4 ++++ 3 files changed, 25 insertions(+) diff --git a/README.md b/README.md index 15725a3..8dfb7e4 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ Or you can just dump `dash.el` in your load path somewhere. * [-none?](#-none-fn-list) `(fn list)` * [-each](#-each-list-fn) `(list fn)` * [-each-while](#-each-while-list-pred-fn) `(list pred fn)` +* [-dotimes](#-dotimes-num-fn) `(num fn)` * [-take](#-take-n-list) `(n list)` * [-drop](#-drop-n-list) `(n list)` * [-take-while](#-take-while-fn-list) `(fn list)` @@ -238,6 +239,15 @@ Returns nil, used for side-effects only. (let (s) (--each-while '(1 2 3 4) (< it 3) (!cons it s)) s) ;; => '(2 1) ``` +### -dotimes `(num fn)` + +Repeatedly calls `fn` (presumably for side-effects) passing in integers from 0 through n-1. + +```cl +(let (s) (-dotimes 3 (lambda (n) (!cons n s))) s) ;; => '(2 1 0) +(let (s) (--dotimes 5 (!cons it s)) s) ;; => '(4 3 2 1 0) +``` + ### -take `(n list)` Returns a new list of the first `n` items in `list`, or all items if there are fewer than `n`. diff --git a/dash.el b/dash.el index 7a81131..18ebb54 100644 --- a/dash.el +++ b/dash.el @@ -64,6 +64,17 @@ Returns nil, used for side-effects only." (--each-while list (funcall pred it) (funcall fn it))) +(defmacro --dotimes (num &rest body) + "Repeatedly executes BODY (presumably for side-effects) with `it` bound to integers from 0 through n-1." + `(let ((it 0)) + (while (< it ,num) + ,@body + (setq it (1+ it))))) + +(defun -dotimes (num fn) + "Repeatedly calls FN (presumably for side-effects) passing in integers from 0 through n-1." + (--dotimes num (funcall fn it))) + (defun -map (fn list) "Returns a new list consisting of the result of applying FN to the items in LIST." (mapcar fn list)) diff --git a/examples.el b/examples.el index a0aca3a..e5eb0f5 100644 --- a/examples.el +++ b/examples.el @@ -87,6 +87,10 @@ (let (s) (-each-while '(2 4 5 6) 'even? (lambda (item) (!cons item s))) s) => '(4 2) (let (s) (--each-while '(1 2 3 4) (< it 3) (!cons it s)) s) => '(2 1)) +(defexamples -dotimes + (let (s) (-dotimes 3 (lambda (n) (!cons n s))) s) => '(2 1 0) + (let (s) (--dotimes 5 (!cons it s)) s) => '(4 3 2 1 0)) + (defexamples -take (-take 3 '(1 2 3 4 5)) => '(1 2 3) (-take 17 '(1 2 3 4 5)) => '(1 2 3 4 5))