Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3072 lines
102 KiB

  1. ;;; dash.el --- A modern list library for Emacs -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2012-2016 Free Software Foundation, Inc.
  3. ;; Author: Magnar Sveen <magnars@gmail.com>
  4. ;; Version: 2.17.0
  5. ;; Keywords: lists
  6. ;; This program is free software; you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; This program is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; A modern list api for Emacs.
  18. ;;
  19. ;; See documentation on https://github.com/magnars/dash.el#functions
  20. ;;
  21. ;; **Please note** The lexical binding in this file is not utilised at the
  22. ;; moment. We will take full advantage of lexical binding in an upcoming 3.0
  23. ;; release of Dash. In the meantime, we've added the pragma to avoid a bug that
  24. ;; you can read more about in https://github.com/magnars/dash.el/issues/130.
  25. ;;
  26. ;;; Code:
  27. ;; TODO: `gv' was introduced in Emacs 24.3, so remove this and all
  28. ;; calls to `defsetf' when support for earlier versions is dropped.
  29. (eval-when-compile
  30. (unless (fboundp 'gv-define-setter)
  31. (require 'cl)))
  32. (defgroup dash ()
  33. "Customize group for dash.el"
  34. :group 'lisp
  35. :prefix "dash-")
  36. (defun dash--enable-fontlock (symbol value)
  37. (when value
  38. (dash-enable-font-lock))
  39. (set-default symbol value))
  40. (defcustom dash-enable-fontlock nil
  41. "If non-nil, enable fontification of dash functions, macros and
  42. special values."
  43. :type 'boolean
  44. :set 'dash--enable-fontlock
  45. :group 'dash)
  46. (defmacro !cons (car cdr)
  47. "Destructive: Set CDR to the cons of CAR and CDR."
  48. `(setq ,cdr (cons ,car ,cdr)))
  49. (defmacro !cdr (list)
  50. "Destructive: Set LIST to the cdr of LIST."
  51. `(setq ,list (cdr ,list)))
  52. (defmacro --each (list &rest body)
  53. "Anaphoric form of `-each'."
  54. (declare (debug (form body))
  55. (indent 1))
  56. (let ((l (make-symbol "list")))
  57. `(let ((,l ,list)
  58. (it-index 0))
  59. (while ,l
  60. (let ((it (car ,l)))
  61. ,@body)
  62. (setq it-index (1+ it-index))
  63. (!cdr ,l)))))
  64. (defmacro -doto (eval-initial-value &rest forms)
  65. "Eval a form, then insert that form as the 2nd argument to other forms.
  66. The EVAL-INITIAL-VALUE form is evaluated once. Its result is
  67. passed to FORMS, which are then evaluated sequentially. Returns
  68. the target form."
  69. (declare (indent 1))
  70. (let ((retval (make-symbol "value")))
  71. `(let ((,retval ,eval-initial-value))
  72. ,@(mapcar (lambda (form)
  73. (if (sequencep form)
  74. `(,(-first-item form) ,retval ,@(cdr form))
  75. `(funcall form ,retval)))
  76. forms)
  77. ,retval)))
  78. (defmacro --doto (eval-initial-value &rest forms)
  79. "Anaphoric form of `-doto'.
  80. Note: `it' is not required in each form."
  81. (declare (indent 1))
  82. `(let ((it ,eval-initial-value))
  83. ,@forms
  84. it))
  85. (defun -each (list fn)
  86. "Call FN with every item in LIST. Return nil, used for side-effects only."
  87. (--each list (funcall fn it)))
  88. (put '-each 'lisp-indent-function 1)
  89. (defalias '--each-indexed '--each)
  90. (defun -each-indexed (list fn)
  91. "Call (FN index item) for each item in LIST.
  92. In the anaphoric form `--each-indexed', the index is exposed as symbol `it-index'.
  93. See also: `-map-indexed'."
  94. (--each list (funcall fn it-index it)))
  95. (put '-each-indexed 'lisp-indent-function 1)
  96. (defmacro --each-while (list pred &rest body)
  97. "Anaphoric form of `-each-while'."
  98. (declare (debug (form form body))
  99. (indent 2))
  100. (let ((l (make-symbol "list"))
  101. (c (make-symbol "continue")))
  102. `(let ((,l ,list)
  103. (,c t)
  104. (it-index 0))
  105. (while (and ,l ,c)
  106. (let ((it (car ,l)))
  107. (if (not ,pred) (setq ,c nil) ,@body))
  108. (setq it-index (1+ it-index))
  109. (!cdr ,l)))))
  110. (defun -each-while (list pred fn)
  111. "Call FN with every item in LIST while (PRED item) is non-nil.
  112. Return nil, used for side-effects only."
  113. (--each-while list (funcall pred it) (funcall fn it)))
  114. (put '-each-while 'lisp-indent-function 2)
  115. (defmacro --each-r (list &rest body)
  116. "Anaphoric form of `-each-r'."
  117. (declare (debug (form body))
  118. (indent 1))
  119. (let ((v (make-symbol "vector")))
  120. ;; Implementation note: building vector is considerably faster
  121. ;; than building a reversed list (vector takes less memory, so
  122. ;; there is less GC), plus length comes naturally. In-place
  123. ;; 'nreverse' would be faster still, but BODY would be able to see
  124. ;; that, even if modification was reversed before we return.
  125. `(let* ((,v (vconcat ,list))
  126. (it-index (length ,v))
  127. it)
  128. (while (> it-index 0)
  129. (setq it-index (1- it-index))
  130. (setq it (aref ,v it-index))
  131. ,@body))))
  132. (defun -each-r (list fn)
  133. "Call FN with every item in LIST in reversed order.
  134. Return nil, used for side-effects only."
  135. (--each-r list (funcall fn it)))
  136. (defmacro --each-r-while (list pred &rest body)
  137. "Anaphoric form of `-each-r-while'."
  138. (declare (debug (form form body))
  139. (indent 2))
  140. (let ((v (make-symbol "vector")))
  141. `(let* ((,v (vconcat ,list))
  142. (it-index (length ,v))
  143. it)
  144. (while (> it-index 0)
  145. (setq it-index (1- it-index))
  146. (setq it (aref ,v it-index))
  147. (if (not ,pred)
  148. (setq it-index -1)
  149. ,@body)))))
  150. (defun -each-r-while (list pred fn)
  151. "Call FN with every item in reversed LIST while (PRED item) is non-nil.
  152. Return nil, used for side-effects only."
  153. (--each-r-while list (funcall pred it) (funcall fn it)))
  154. (defmacro --dotimes (num &rest body)
  155. "Repeatedly executes BODY (presumably for side-effects) with symbol `it' bound to integers from 0 through NUM-1."
  156. (declare (debug (form body))
  157. (indent 1))
  158. (let ((n (make-symbol "num")))
  159. `(let ((,n ,num)
  160. (it 0))
  161. (while (< it ,n)
  162. ,@body
  163. (setq it (1+ it))))))
  164. (defun -dotimes (num fn)
  165. "Repeatedly calls FN (presumably for side-effects) passing in integers from 0 through NUM-1."
  166. (--dotimes num (funcall fn it)))
  167. (put '-dotimes 'lisp-indent-function 1)
  168. (defun -map (fn list)
  169. "Return a new list consisting of the result of applying FN to the items in LIST."
  170. (mapcar fn list))
  171. (defmacro --map (form list)
  172. "Anaphoric form of `-map'."
  173. (declare (debug (form form)))
  174. `(mapcar (lambda (it) ,form) ,list))
  175. (defmacro --reduce-from (form initial-value list)
  176. "Anaphoric form of `-reduce-from'."
  177. (declare (debug (form form form)))
  178. `(let ((acc ,initial-value))
  179. (--each ,list (setq acc ,form))
  180. acc))
  181. (defun -reduce-from (fn initial-value list)
  182. "Return the result of applying FN to INITIAL-VALUE and the
  183. first item in LIST, then applying FN to that result and the 2nd
  184. item, etc. If LIST contains no items, return INITIAL-VALUE and
  185. do not call FN.
  186. In the anaphoric form `--reduce-from', the accumulated value is
  187. exposed as symbol `acc'.
  188. See also: `-reduce', `-reduce-r'"
  189. (--reduce-from (funcall fn acc it) initial-value list))
  190. (defmacro --reduce (form list)
  191. "Anaphoric form of `-reduce'."
  192. (declare (debug (form form)))
  193. (let ((lv (make-symbol "list-value")))
  194. `(let ((,lv ,list))
  195. (if ,lv
  196. (--reduce-from ,form (car ,lv) (cdr ,lv))
  197. (let (acc it) ,form)))))
  198. (defun -reduce (fn list)
  199. "Return the result of applying FN to the first 2 items in LIST,
  200. then applying FN to that result and the 3rd item, etc. If LIST
  201. contains no items, return the result of calling FN with no
  202. arguments. If LIST contains a single item, return that item
  203. and do not call FN.
  204. In the anaphoric form `--reduce', the accumulated value is
  205. exposed as symbol `acc'.
  206. See also: `-reduce-from', `-reduce-r'"
  207. (if list
  208. (-reduce-from fn (car list) (cdr list))
  209. (funcall fn)))
  210. (defmacro --reduce-r-from (form initial-value list)
  211. "Anaphoric version of `-reduce-r-from'."
  212. (declare (debug (form form form)))
  213. `(--reduce-from ,form ,initial-value (reverse ,list)))
  214. (defun -reduce-r-from (fn initial-value list)
  215. "Replace conses with FN, nil with INITIAL-VALUE and evaluate
  216. the resulting expression. If LIST is empty, INITIAL-VALUE is
  217. returned and FN is not called.
  218. Note: this function works the same as `-reduce-from' but the
  219. operation associates from right instead of from left.
  220. See also: `-reduce-r', `-reduce'"
  221. (--reduce-r-from (funcall fn it acc) initial-value list))
  222. (defmacro --reduce-r (form list)
  223. "Anaphoric version of `-reduce-r'."
  224. (declare (debug (form form)))
  225. `(--reduce ,form (reverse ,list)))
  226. (defun -reduce-r (fn list)
  227. "Replace conses with FN and evaluate the resulting expression.
  228. The final nil is ignored. If LIST contains no items, return the
  229. result of calling FN with no arguments. If LIST contains a single
  230. item, return that item and do not call FN.
  231. The first argument of FN is the new item, the second is the
  232. accumulated value.
  233. Note: this function works the same as `-reduce' but the operation
  234. associates from right instead of from left.
  235. See also: `-reduce-r-from', `-reduce'"
  236. (if list
  237. (--reduce-r (funcall fn it acc) list)
  238. (funcall fn)))
  239. (defun -reductions-from (fn init list)
  240. "Return a list of the intermediate values of the reduction.
  241. See `-reduce-from' for explanation of the arguments.
  242. See also: `-reductions', `-reductions-r', `-reduce-r'"
  243. (nreverse (--reduce-from (cons (funcall fn (car acc) it) acc) (list init) list)))
  244. (defun -reductions (fn list)
  245. "Return a list of the intermediate values of the reduction.
  246. See `-reduce' for explanation of the arguments.
  247. See also: `-reductions-from', `-reductions-r', `-reduce-r'"
  248. (and list (-reductions-from fn (car list) (cdr list))))
  249. (defun -reductions-r-from (fn init list)
  250. "Return a list of the intermediate values of the reduction.
  251. See `-reduce-r-from' for explanation of the arguments.
  252. See also: `-reductions-r', `-reductions', `-reduce'"
  253. (--reduce-r-from (cons (funcall fn it (car acc)) acc) (list init) list))
  254. (defun -reductions-r (fn list)
  255. "Return a list of the intermediate values of the reduction.
  256. See `-reduce-r' for explanation of the arguments.
  257. See also: `-reductions-r-from', `-reductions', `-reduce'"
  258. (when list
  259. (let ((rev (reverse list)))
  260. (--reduce-from (cons (funcall fn it (car acc)) acc)
  261. (list (car rev))
  262. (cdr rev)))))
  263. (defmacro --filter (form list)
  264. "Anaphoric form of `-filter'.
  265. See also: `--remove'."
  266. (declare (debug (form form)))
  267. (let ((r (make-symbol "result")))
  268. `(let (,r)
  269. (--each ,list (when ,form (!cons it ,r)))
  270. (nreverse ,r))))
  271. (defun -filter (pred list)
  272. "Return a new list of the items in LIST for which PRED returns a non-nil value.
  273. Alias: `-select'
  274. See also: `-keep', `-remove'."
  275. (--filter (funcall pred it) list))
  276. (defalias '-select '-filter)
  277. (defalias '--select '--filter)
  278. (defmacro --remove (form list)
  279. "Anaphoric form of `-remove'.
  280. See also `--filter'."
  281. (declare (debug (form form)))
  282. `(--filter (not ,form) ,list))
  283. (defun -remove (pred list)
  284. "Return a new list of the items in LIST for which PRED returns nil.
  285. Alias: `-reject'
  286. See also: `-filter'."
  287. (--remove (funcall pred it) list))
  288. (defalias '-reject '-remove)
  289. (defalias '--reject '--remove)
  290. (defun -remove-first (pred list)
  291. "Return a new list with the first item matching PRED removed.
  292. Alias: `-reject-first'
  293. See also: `-remove', `-map-first'"
  294. (let (front)
  295. (while (and list (not (funcall pred (car list))))
  296. (push (car list) front)
  297. (!cdr list))
  298. (if list
  299. (-concat (nreverse front) (cdr list))
  300. (nreverse front))))
  301. (defmacro --remove-first (form list)
  302. "Anaphoric form of `-remove-first'."
  303. (declare (debug (form form)))
  304. `(-remove-first (lambda (it) ,form) ,list))
  305. (defalias '-reject-first '-remove-first)
  306. (defalias '--reject-first '--remove-first)
  307. (defun -remove-last (pred list)
  308. "Return a new list with the last item matching PRED removed.
  309. Alias: `-reject-last'
  310. See also: `-remove', `-map-last'"
  311. (nreverse (-remove-first pred (reverse list))))
  312. (defmacro --remove-last (form list)
  313. "Anaphoric form of `-remove-last'."
  314. (declare (debug (form form)))
  315. `(-remove-last (lambda (it) ,form) ,list))
  316. (defalias '-reject-last '-remove-last)
  317. (defalias '--reject-last '--remove-last)
  318. (defun -remove-item (item list)
  319. "Remove all occurrences of ITEM from LIST.
  320. Comparison is done with `equal'."
  321. (declare (pure t) (side-effect-free t))
  322. (--remove (equal it item) list))
  323. (defmacro --keep (form list)
  324. "Anaphoric form of `-keep'."
  325. (declare (debug (form form)))
  326. (let ((r (make-symbol "result"))
  327. (m (make-symbol "mapped")))
  328. `(let (,r)
  329. (--each ,list (let ((,m ,form)) (when ,m (!cons ,m ,r))))
  330. (nreverse ,r))))
  331. (defun -keep (fn list)
  332. "Return a new list of the non-nil results of applying FN to the items in LIST.
  333. If you want to select the original items satisfying a predicate use `-filter'."
  334. (--keep (funcall fn it) list))
  335. (defun -non-nil (list)
  336. "Return all non-nil elements of LIST."
  337. (declare (pure t) (side-effect-free t))
  338. (-remove 'null list))
  339. (defmacro --map-indexed (form list)
  340. "Anaphoric form of `-map-indexed'."
  341. (declare (debug (form form)))
  342. (let ((r (make-symbol "result")))
  343. `(let (,r)
  344. (--each ,list
  345. (!cons ,form ,r))
  346. (nreverse ,r))))
  347. (defun -map-indexed (fn list)
  348. "Return a new list consisting of the result of (FN index item) for each item in LIST.
  349. In the anaphoric form `--map-indexed', the index is exposed as symbol `it-index'.
  350. See also: `-each-indexed'."
  351. (--map-indexed (funcall fn it-index it) list))
  352. (defmacro --map-when (pred rep list)
  353. "Anaphoric form of `-map-when'."
  354. (declare (debug (form form form)))
  355. (let ((r (make-symbol "result")))
  356. `(let (,r)
  357. (--each ,list (!cons (if ,pred ,rep it) ,r))
  358. (nreverse ,r))))
  359. (defun -map-when (pred rep list)
  360. "Return a new list where the elements in LIST that do not match the PRED function
  361. are unchanged, and where the elements in LIST that do match the PRED function are mapped
  362. through the REP function.
  363. Alias: `-replace-where'
  364. See also: `-update-at'"
  365. (--map-when (funcall pred it) (funcall rep it) list))
  366. (defalias '-replace-where '-map-when)
  367. (defalias '--replace-where '--map-when)
  368. (defun -map-first (pred rep list)
  369. "Replace first item in LIST satisfying PRED with result of REP called on this item.
  370. See also: `-map-when', `-replace-first'"
  371. (let (front)
  372. (while (and list (not (funcall pred (car list))))
  373. (push (car list) front)
  374. (!cdr list))
  375. (if list
  376. (-concat (nreverse front) (cons (funcall rep (car list)) (cdr list)))
  377. (nreverse front))))
  378. (defmacro --map-first (pred rep list)
  379. "Anaphoric form of `-map-first'."
  380. `(-map-first (lambda (it) ,pred) (lambda (it) (ignore it) ,rep) ,list))
  381. (defun -map-last (pred rep list)
  382. "Replace last item in LIST satisfying PRED with result of REP called on this item.
  383. See also: `-map-when', `-replace-last'"
  384. (nreverse (-map-first pred rep (reverse list))))
  385. (defmacro --map-last (pred rep list)
  386. "Anaphoric form of `-map-last'."
  387. `(-map-last (lambda (it) ,pred) (lambda (it) (ignore it) ,rep) ,list))
  388. (defun -replace (old new list)
  389. "Replace all OLD items in LIST with NEW.
  390. Elements are compared using `equal'.
  391. See also: `-replace-at'"
  392. (declare (pure t) (side-effect-free t))
  393. (--map-when (equal it old) new list))
  394. (defun -replace-first (old new list)
  395. "Replace the first occurrence of OLD with NEW in LIST.
  396. Elements are compared using `equal'.
  397. See also: `-map-first'"
  398. (declare (pure t) (side-effect-free t))
  399. (--map-first (equal old it) new list))
  400. (defun -replace-last (old new list)
  401. "Replace the last occurrence of OLD with NEW in LIST.
  402. Elements are compared using `equal'.
  403. See also: `-map-last'"
  404. (declare (pure t) (side-effect-free t))
  405. (--map-last (equal old it) new list))
  406. (defmacro --mapcat (form list)
  407. "Anaphoric form of `-mapcat'."
  408. (declare (debug (form form)))
  409. `(apply 'append (--map ,form ,list)))
  410. (defun -mapcat (fn list)
  411. "Return the concatenation of the result of mapping FN over LIST.
  412. Thus function FN should return a list."
  413. (--mapcat (funcall fn it) list))
  414. (defun -flatten (l)
  415. "Take a nested list L and return its contents as a single, flat list.
  416. Note that because `nil' represents a list of zero elements (an
  417. empty list), any mention of nil in L will disappear after
  418. flattening. If you need to preserve nils, consider `-flatten-n'
  419. or map them to some unique symbol and then map them back.
  420. Conses of two atoms are considered \"terminals\", that is, they
  421. aren't flattened further.
  422. See also: `-flatten-n'"
  423. (declare (pure t) (side-effect-free t))
  424. (if (and (listp l) (listp (cdr l)))
  425. (-mapcat '-flatten l)
  426. (list l)))
  427. (defmacro --iterate (form init n)
  428. "Anaphoric version of `-iterate'."
  429. (declare (debug (form form form)))
  430. `(-iterate (lambda (it) ,form) ,init ,n))
  431. (defun -flatten-n (num list)
  432. "Flatten NUM levels of a nested LIST.
  433. See also: `-flatten'"
  434. (declare (pure t) (side-effect-free t))
  435. (-last-item (--iterate (--mapcat (-list it) it) list (1+ num))))
  436. (defun -concat (&rest lists)
  437. "Return a new list with the concatenation of the elements in the supplied LISTS."
  438. (declare (pure t) (side-effect-free t))
  439. (apply 'append lists))
  440. (defalias '-copy 'copy-sequence
  441. "Create a shallow copy of LIST.
  442. \(fn LIST)")
  443. (defun -splice (pred fun list)
  444. "Splice lists generated by FUN in place of elements matching PRED in LIST.
  445. FUN takes the element matching PRED as input.
  446. This function can be used as replacement for `,@' in case you
  447. need to splice several lists at marked positions (for example
  448. with keywords).
  449. See also: `-splice-list', `-insert-at'"
  450. (let (r)
  451. (--each list
  452. (if (funcall pred it)
  453. (let ((new (funcall fun it)))
  454. (--each new (!cons it r)))
  455. (!cons it r)))
  456. (nreverse r)))
  457. (defmacro --splice (pred form list)
  458. "Anaphoric form of `-splice'."
  459. `(-splice (lambda (it) ,pred) (lambda (it) ,form) ,list))
  460. (defun -splice-list (pred new-list list)
  461. "Splice NEW-LIST in place of elements matching PRED in LIST.
  462. See also: `-splice', `-insert-at'"
  463. (-splice pred (lambda (_) new-list) list))
  464. (defmacro --splice-list (pred new-list list)
  465. "Anaphoric form of `-splice-list'."
  466. `(-splice-list (lambda (it) ,pred) ,new-list ,list))
  467. (defun -cons* (&rest args)
  468. "Make a new list from the elements of ARGS.
  469. The last 2 members of ARGS are used as the final cons of the
  470. result so if the final member of ARGS is not a list the result is
  471. a dotted list."
  472. (declare (pure t) (side-effect-free t))
  473. (-reduce-r 'cons args))
  474. (defun -snoc (list elem &rest elements)
  475. "Append ELEM to the end of the list.
  476. This is like `cons', but operates on the end of list.
  477. If ELEMENTS is non nil, append these to the list as well."
  478. (-concat list (list elem) elements))
  479. (defmacro --first (form list)
  480. "Anaphoric form of `-first'."
  481. (declare (debug (form form)))
  482. (let ((n (make-symbol "needle")))
  483. `(let (,n)
  484. (--each-while ,list (not ,n)
  485. (when ,form (setq ,n it)))
  486. ,n)))
  487. (defun -first (pred list)
  488. "Return the first x in LIST where (PRED x) is non-nil, else nil.
  489. To get the first item in the list no questions asked, use `car'.
  490. Alias: `-find'"
  491. (--first (funcall pred it) list))
  492. (defalias '-find '-first)
  493. (defalias '--find '--first)
  494. (defmacro --some (form list)
  495. "Anaphoric form of `-some'."
  496. (declare (debug (form form)))
  497. (let ((n (make-symbol "needle")))
  498. `(let (,n)
  499. (--each-while ,list (not ,n)
  500. (setq ,n ,form))
  501. ,n)))
  502. (defun -some (pred list)
  503. "Return (PRED x) for the first LIST item where (PRED x) is non-nil, else nil.
  504. Alias: `-any'"
  505. (--some (funcall pred it) list))
  506. (defalias '-any '-some)
  507. (defalias '--any '--some)
  508. (defmacro --last (form list)
  509. "Anaphoric form of `-last'."
  510. (declare (debug (form form)))
  511. (let ((n (make-symbol "needle")))
  512. `(let (,n)
  513. (--each ,list
  514. (when ,form (setq ,n it)))
  515. ,n)))
  516. (defun -last (pred list)
  517. "Return the last x in LIST where (PRED x) is non-nil, else nil."
  518. (--last (funcall pred it) list))
  519. (defalias '-first-item 'car
  520. "Return the first item of LIST, or nil on an empty list.
  521. See also: `-second-item', `-last-item'.
  522. \(fn LIST)")
  523. ;; Ensure that calls to `-first-item' are compiled to a single opcode,
  524. ;; just like `car'.
  525. (put '-first-item 'byte-opcode 'byte-car)
  526. (put '-first-item 'byte-compile 'byte-compile-one-arg)
  527. (defalias '-second-item 'cadr
  528. "Return the second item of LIST, or nil if LIST is too short.
  529. See also: `-third-item'.
  530. \(fn LIST)")
  531. (defalias '-third-item
  532. (if (fboundp 'caddr)
  533. #'caddr
  534. (lambda (list) (car (cddr list))))
  535. "Return the third item of LIST, or nil if LIST is too short.
  536. See also: `-fourth-item'.
  537. \(fn LIST)")
  538. (defun -fourth-item (list)
  539. "Return the fourth item of LIST, or nil if LIST is too short.
  540. See also: `-fifth-item'."
  541. (declare (pure t) (side-effect-free t))
  542. (car (cdr (cdr (cdr list)))))
  543. (defun -fifth-item (list)
  544. "Return the fifth item of LIST, or nil if LIST is too short.
  545. See also: `-last-item'."
  546. (declare (pure t) (side-effect-free t))
  547. (car (cdr (cdr (cdr (cdr list))))))
  548. (defun -last-item (list)
  549. "Return the last item of LIST, or nil on an empty list."
  550. (declare (pure t) (side-effect-free t))
  551. (car (last list)))
  552. ;; Use `with-no-warnings' to suppress unbound `-last-item' or
  553. ;; undefined `gv--defsetter' warnings arising from both
  554. ;; `gv-define-setter' and `defsetf' in certain Emacs versions.
  555. (with-no-warnings
  556. (if (fboundp 'gv-define-setter)
  557. (gv-define-setter -last-item (val x) `(setcar (last ,x) ,val))
  558. (defsetf -last-item (x) (val) `(setcar (last ,x) ,val))))
  559. (defun -butlast (list)
  560. "Return a list of all items in list except for the last."
  561. ;; no alias as we don't want magic optional argument
  562. (declare (pure t) (side-effect-free t))
  563. (butlast list))
  564. (defmacro --count (pred list)
  565. "Anaphoric form of `-count'."
  566. (declare (debug (form form)))
  567. (let ((r (make-symbol "result")))
  568. `(let ((,r 0))
  569. (--each ,list (when ,pred (setq ,r (1+ ,r))))
  570. ,r)))
  571. (defun -count (pred list)
  572. "Counts the number of items in LIST where (PRED item) is non-nil."
  573. (--count (funcall pred it) list))
  574. (defun ---truthy? (val)
  575. (declare (pure t) (side-effect-free t))
  576. (not (null val)))
  577. (defmacro --any? (form list)
  578. "Anaphoric form of `-any?'."
  579. (declare (debug (form form)))
  580. `(---truthy? (--some ,form ,list)))
  581. (defun -any? (pred list)
  582. "Return t if (PRED x) is non-nil for any x in LIST, else nil.
  583. Alias: `-any-p', `-some?', `-some-p'"
  584. (--any? (funcall pred it) list))
  585. (defalias '-some? '-any?)
  586. (defalias '--some? '--any?)
  587. (defalias '-any-p '-any?)
  588. (defalias '--any-p '--any?)
  589. (defalias '-some-p '-any?)
  590. (defalias '--some-p '--any?)
  591. (defmacro --all? (form list)
  592. "Anaphoric form of `-all?'."
  593. (declare (debug (form form)))
  594. (let ((a (make-symbol "all")))
  595. `(let ((,a t))
  596. (--each-while ,list ,a (setq ,a ,form))
  597. (---truthy? ,a))))
  598. (defun -all? (pred list)
  599. "Return t if (PRED x) is non-nil for all x in LIST, else nil.
  600. Alias: `-all-p', `-every?', `-every-p'"
  601. (--all? (funcall pred it) list))
  602. (defalias '-every? '-all?)
  603. (defalias '--every? '--all?)
  604. (defalias '-all-p '-all?)
  605. (defalias '--all-p '--all?)
  606. (defalias '-every-p '-all?)
  607. (defalias '--every-p '--all?)
  608. (defmacro --none? (form list)
  609. "Anaphoric form of `-none?'."
  610. (declare (debug (form form)))
  611. `(--all? (not ,form) ,list))
  612. (defun -none? (pred list)
  613. "Return t if (PRED x) is nil for all x in LIST, else nil.
  614. Alias: `-none-p'"
  615. (--none? (funcall pred it) list))
  616. (defalias '-none-p '-none?)
  617. (defalias '--none-p '--none?)
  618. (defmacro --only-some? (form list)
  619. "Anaphoric form of `-only-some?'."
  620. (declare (debug (form form)))
  621. (let ((y (make-symbol "yes"))
  622. (n (make-symbol "no")))
  623. `(let (,y ,n)
  624. (--each-while ,list (not (and ,y ,n))
  625. (if ,form (setq ,y t) (setq ,n t)))
  626. (---truthy? (and ,y ,n)))))
  627. (defun -only-some? (pred list)
  628. "Return `t` if at least one item of LIST matches PRED and at least one item of LIST does not match PRED.
  629. Return `nil` both if all items match the predicate or if none of the items match the predicate.
  630. Alias: `-only-some-p'"
  631. (--only-some? (funcall pred it) list))
  632. (defalias '-only-some-p '-only-some?)
  633. (defalias '--only-some-p '--only-some?)
  634. (defun -slice (list from &optional to step)
  635. "Return copy of LIST, starting from index FROM to index TO.
  636. FROM or TO may be negative. These values are then interpreted
  637. modulo the length of the list.
  638. If STEP is a number, only each STEPth item in the resulting
  639. section is returned. Defaults to 1."
  640. (declare (pure t) (side-effect-free t))
  641. (let ((length (length list))
  642. (new-list nil))
  643. ;; to defaults to the end of the list
  644. (setq to (or to length))
  645. (setq step (or step 1))
  646. ;; handle negative indices
  647. (when (< from 0)
  648. (setq from (mod from length)))
  649. (when (< to 0)
  650. (setq to (mod to length)))
  651. ;; iterate through the list, keeping the elements we want
  652. (--each-while list (< it-index to)
  653. (when (and (>= it-index from)
  654. (= (mod (- from it-index) step) 0))
  655. (push it new-list)))
  656. (nreverse new-list)))
  657. (defun -take (n list)
  658. "Return a new list of the first N items in LIST, or all items if there are fewer than N.
  659. See also: `-take-last'"
  660. (declare (pure t) (side-effect-free t))
  661. (let (result)
  662. (--dotimes n
  663. (when list
  664. (!cons (car list) result)
  665. (!cdr list)))
  666. (nreverse result)))
  667. (defun -take-last (n list)
  668. "Return the last N items of LIST in order.
  669. See also: `-take'"
  670. (declare (pure t) (side-effect-free t))
  671. (copy-sequence (last list n)))
  672. (defalias '-drop 'nthcdr
  673. "Return the tail of LIST without the first N items.
  674. See also: `-drop-last'
  675. \(fn N LIST)")
  676. (defun -drop-last (n list)
  677. "Remove the last N items of LIST and return a copy.
  678. See also: `-drop'"
  679. ;; No alias because we don't want magic optional argument
  680. (declare (pure t) (side-effect-free t))
  681. (butlast list n))
  682. (defmacro --take-while (form list)
  683. "Anaphoric form of `-take-while'."
  684. (declare (debug (form form)))
  685. (let ((r (make-symbol "result")))
  686. `(let (,r)
  687. (--each-while ,list ,form (!cons it ,r))
  688. (nreverse ,r))))
  689. (defun -take-while (pred list)
  690. "Return a new list of successive items from LIST while (PRED item) returns a non-nil value."
  691. (--take-while (funcall pred it) list))
  692. (defmacro --drop-while (form list)
  693. "Anaphoric form of `-drop-while'."
  694. (declare (debug (form form)))
  695. (let ((l (make-symbol "list")))
  696. `(let ((,l ,list))
  697. (while (and ,l (let ((it (car ,l))) ,form))
  698. (!cdr ,l))
  699. ,l)))
  700. (defun -drop-while (pred list)
  701. "Return the tail of LIST starting from the first item for which (PRED item) returns nil."
  702. (--drop-while (funcall pred it) list))
  703. (defun -split-at (n list)
  704. "Return a list of ((-take N LIST) (-drop N LIST)), in no more than one pass through the list."
  705. (declare (pure t) (side-effect-free t))
  706. (let (result)
  707. (--dotimes n
  708. (when list
  709. (!cons (car list) result)
  710. (!cdr list)))
  711. (list (nreverse result) list)))
  712. (defun -rotate (n list)
  713. "Rotate LIST N places to the right. With N negative, rotate to the left.
  714. The time complexity is O(n)."
  715. (declare (pure t) (side-effect-free t))
  716. (when list
  717. (let* ((len (length list))
  718. (n-mod-len (mod n len))
  719. (new-tail-len (- len n-mod-len)))
  720. (append (-drop new-tail-len list) (-take new-tail-len list)))))
  721. (defun -insert-at (n x list)
  722. "Return a list with X inserted into LIST at position N.
  723. See also: `-splice', `-splice-list'"
  724. (declare (pure t) (side-effect-free t))
  725. (let ((split-list (-split-at n list)))
  726. (nconc (car split-list) (cons x (cadr split-list)))))
  727. (defun -replace-at (n x list)
  728. "Return a list with element at Nth position in LIST replaced with X.
  729. See also: `-replace'"
  730. (declare (pure t) (side-effect-free t))
  731. (let ((split-list (-split-at n list)))
  732. (nconc (car split-list) (cons x (cdr (cadr split-list))))))
  733. (defun -update-at (n func list)
  734. "Return a list with element at Nth position in LIST replaced with `(func (nth n list))`.
  735. See also: `-map-when'"
  736. (let ((split-list (-split-at n list)))
  737. (nconc (car split-list) (cons (funcall func (car (cadr split-list))) (cdr (cadr split-list))))))
  738. (defmacro --update-at (n form list)
  739. "Anaphoric version of `-update-at'."
  740. (declare (debug (form form form)))
  741. `(-update-at ,n (lambda (it) ,form) ,list))
  742. (defun -remove-at (n list)
  743. "Return a list with element at Nth position in LIST removed.
  744. See also: `-remove-at-indices', `-remove'"
  745. (declare (pure t) (side-effect-free t))
  746. (-remove-at-indices (list n) list))
  747. (defun -remove-at-indices (indices list)
  748. "Return a list whose elements are elements from LIST without
  749. elements selected as `(nth i list)` for all i
  750. from INDICES.
  751. See also: `-remove-at', `-remove'"
  752. (declare (pure t) (side-effect-free t))
  753. (let* ((indices (-sort '< indices))
  754. (diffs (cons (car indices) (-map '1- (-zip-with '- (cdr indices) indices))))
  755. r)
  756. (--each diffs
  757. (let ((split (-split-at it list)))
  758. (!cons (car split) r)
  759. (setq list (cdr (cadr split)))))
  760. (!cons list r)
  761. (apply '-concat (nreverse r))))
  762. (defmacro --split-with (pred list)
  763. "Anaphoric form of `-split-with'."
  764. (declare (debug (form form)))
  765. (let ((l (make-symbol "list"))
  766. (r (make-symbol "result"))
  767. (c (make-symbol "continue")))
  768. `(let ((,l ,list)
  769. (,r nil)
  770. (,c t))
  771. (while (and ,l ,c)
  772. (let ((it (car ,l)))
  773. (if (not ,pred)
  774. (setq ,c nil)
  775. (!cons it ,r)
  776. (!cdr ,l))))
  777. (list (nreverse ,r) ,l))))
  778. (defun -split-with (pred list)
  779. "Return a list of ((-take-while PRED LIST) (-drop-while PRED LIST)), in no more than one pass through the list."
  780. (--split-with (funcall pred it) list))
  781. (defmacro -split-on (item list)
  782. "Split the LIST each time ITEM is found.
  783. Unlike `-partition-by', the ITEM is discarded from the results.
  784. Empty lists are also removed from the result.
  785. Comparison is done by `equal'.
  786. See also `-split-when'"
  787. (declare (debug (form form)))
  788. `(-split-when (lambda (it) (equal it ,item)) ,list))
  789. (defmacro --split-when (form list)
  790. "Anaphoric version of `-split-when'."
  791. (declare (debug (form form)))
  792. `(-split-when (lambda (it) ,form) ,list))
  793. (defun -split-when (fn list)
  794. "Split the LIST on each element where FN returns non-nil.
  795. Unlike `-partition-by', the \"matched\" element is discarded from
  796. the results. Empty lists are also removed from the result.
  797. This function can be thought of as a generalization of
  798. `split-string'."
  799. (let (r s)
  800. (while list
  801. (if (not (funcall fn (car list)))
  802. (push (car list) s)
  803. (when s (push (nreverse s) r))
  804. (setq s nil))
  805. (!cdr list))
  806. (when s (push (nreverse s) r))
  807. (nreverse r)))
  808. (defmacro --separate (form list)
  809. "Anaphoric form of `-separate'."
  810. (declare (debug (form form)))
  811. (let ((y (make-symbol "yes"))
  812. (n (make-symbol "no")))
  813. `(let (,y ,n)
  814. (--each ,list (if ,form (!cons it ,y) (!cons it ,n)))
  815. (list (nreverse ,y) (nreverse ,n)))))
  816. (defun -separate (pred list)
  817. "Return a list of ((-filter PRED LIST) (-remove PRED LIST)), in one pass through the list."
  818. (--separate (funcall pred it) list))
  819. (defun ---partition-all-in-steps-reversed (n step list)
  820. "Private: Used by -partition-all-in-steps and -partition-in-steps."
  821. (when (< step 1)
  822. (error "Step must be a positive number, or you're looking at some juicy infinite loops."))
  823. (let ((result nil))
  824. (while list
  825. (!cons (-take n list) result)
  826. (setq list (-drop step list)))
  827. result))
  828. (defun -partition-all-in-steps (n step list)
  829. "Return a new list with the items in LIST grouped into N-sized sublists at offsets STEP apart.
  830. The last groups may contain less than N items."
  831. (declare (pure t) (side-effect-free t))
  832. (nreverse (---partition-all-in-steps-reversed n step list)))
  833. (defun -partition-in-steps (n step list)
  834. "Return a new list with the items in LIST grouped into N-sized sublists at offsets STEP apart.
  835. If there are not enough items to make the last group N-sized,
  836. those items are discarded."
  837. (declare (pure t) (side-effect-free t))
  838. (let ((result (---partition-all-in-steps-reversed n step list)))
  839. (while (and result (< (length (car result)) n))
  840. (!cdr result))
  841. (nreverse result)))
  842. (defun -partition-all (n list)
  843. "Return a new list with the items in LIST grouped into N-sized sublists.
  844. The last group may contain less than N items."
  845. (declare (pure t) (side-effect-free t))
  846. (-partition-all-in-steps n n list))
  847. (defun -partition (n list)
  848. "Return a new list with the items in LIST grouped into N-sized sublists.
  849. If there are not enough items to make the last group N-sized,
  850. those items are discarded."
  851. (declare (pure t) (side-effect-free t))
  852. (-partition-in-steps n n list))
  853. (defmacro --partition-by (form list)
  854. "Anaphoric form of `-partition-by'."
  855. (declare (debug (form form)))
  856. (let ((r (make-symbol "result"))
  857. (s (make-symbol "sublist"))
  858. (v (make-symbol "value"))
  859. (n (make-symbol "new-value"))
  860. (l (make-symbol "list")))
  861. `(let ((,l ,list))
  862. (when ,l
  863. (let* ((,r nil)
  864. (it (car ,l))
  865. (,s (list it))
  866. (,v ,form)
  867. (,l (cdr ,l)))
  868. (while ,l
  869. (let* ((it (car ,l))
  870. (,n ,form))
  871. (unless (equal ,v ,n)
  872. (!cons (nreverse ,s) ,r)
  873. (setq ,s nil)
  874. (setq ,v ,n))
  875. (!cons it ,s)
  876. (!cdr ,l)))
  877. (!cons (nreverse ,s) ,r)
  878. (nreverse ,r))))))
  879. (defun -partition-by (fn list)
  880. "Apply FN to each item in LIST, splitting it each time FN returns a new value."
  881. (--partition-by (funcall fn it) list))
  882. (defmacro --partition-by-header (form list)
  883. "Anaphoric form of `-partition-by-header'."
  884. (declare (debug (form form)))
  885. (let ((r (make-symbol "result"))
  886. (s (make-symbol "sublist"))
  887. (h (make-symbol "header-value"))
  888. (b (make-symbol "seen-body?"))
  889. (n (make-symbol "new-value"))
  890. (l (make-symbol "list")))
  891. `(let ((,l ,list))
  892. (when ,l
  893. (let* ((,r nil)
  894. (it (car ,l))
  895. (,s (list it))
  896. (,h ,form)
  897. (,b nil)
  898. (,l (cdr ,l)))
  899. (while ,l
  900. (let* ((it (car ,l))
  901. (,n ,form))
  902. (if (equal ,h ,n)
  903. (when ,b
  904. (!cons (nreverse ,s) ,r)
  905. (setq ,s nil)
  906. (setq ,b nil))
  907. (setq ,b t))
  908. (!cons it ,s)
  909. (!cdr ,l)))
  910. (!cons (nreverse ,s) ,r)
  911. (nreverse ,r))))))
  912. (defun -partition-by-header (fn list)
  913. "Apply FN to the first item in LIST. That is the header
  914. value. Apply FN to each item in LIST, splitting it each time FN
  915. returns the header value, but only after seeing at least one
  916. other value (the body)."
  917. (--partition-by-header (funcall fn it) list))
  918. (defun -partition-after-pred (pred list)
  919. "Partition directly after each time PRED is true on an element of LIST."
  920. (when list
  921. (let ((rest (-partition-after-pred pred
  922. (cdr list))))
  923. (if (funcall pred (car list))
  924. ;;split after (car list)
  925. (cons (list (car list))
  926. rest)
  927. ;;don't split after (car list)
  928. (cons (cons (car list)
  929. (car rest))
  930. (cdr rest))))))
  931. (defun -partition-before-pred (pred list)
  932. "Partition directly before each time PRED is true on an element of LIST."
  933. (nreverse (-map #'reverse
  934. (-partition-after-pred pred (reverse list)))))
  935. (defun -partition-after-item (item list)
  936. "Partition directly after each time ITEM appears in LIST."
  937. (-partition-after-pred (lambda (ele) (equal ele item))
  938. list))
  939. (defun -partition-before-item (item list)
  940. "Partition directly before each time ITEM appears in LIST."
  941. (-partition-before-pred (lambda (ele) (equal ele item))
  942. list))
  943. (defmacro --group-by (form list)
  944. "Anaphoric form of `-group-by'."
  945. (declare (debug t))
  946. (let ((n (make-symbol "n"))
  947. (k (make-symbol "k"))
  948. (grp (make-symbol "grp")))
  949. `(nreverse
  950. (-map
  951. (lambda (,n)
  952. (cons (car ,n)
  953. (nreverse (cdr ,n))))
  954. (--reduce-from
  955. (let* ((,k (,@form))
  956. (,grp (assoc ,k acc)))
  957. (if ,grp
  958. (setcdr ,grp (cons it (cdr ,grp)))
  959. (push
  960. (list ,k it)
  961. acc))
  962. acc)
  963. nil ,list)))))
  964. (defun -group-by (fn list)
  965. "Separate LIST into an alist whose keys are FN applied to the
  966. elements of LIST. Keys are compared by `equal'."
  967. (--group-by (funcall fn it) list))
  968. (defun -interpose (sep list)
  969. "Return a new list of all elements in LIST separated by SEP."
  970. (declare (pure t) (side-effect-free t))
  971. (let (result)
  972. (when list
  973. (!cons (car list) result)
  974. (!cdr list))
  975. (while list
  976. (setq result (cons (car list) (cons sep result)))
  977. (!cdr list))
  978. (nreverse result)))
  979. (defun -interleave (&rest lists)
  980. "Return a new list of the first item in each list, then the second etc."
  981. (declare (pure t) (side-effect-free t))
  982. (when lists
  983. (let (result)
  984. (while (-none? 'null lists)
  985. (--each lists (!cons (car it) result))
  986. (setq lists (-map 'cdr lists)))
  987. (nreverse result))))
  988. (defmacro --zip-with (form list1 list2)
  989. "Anaphoric form of `-zip-with'.
  990. The elements in list1 are bound as symbol `it', the elements in list2 as symbol `other'."
  991. (declare (debug (form form form)))
  992. (let ((r (make-symbol "result"))
  993. (l1 (make-symbol "list1"))
  994. (l2 (make-symbol "list2")))
  995. `(let ((,r nil)
  996. (,l1 ,list1)
  997. (,l2 ,list2))
  998. (while (and ,l1 ,l2)
  999. (let ((it (car ,l1))
  1000. (other (car ,l2)))
  1001. (!cons ,form ,r)
  1002. (!cdr ,l1)
  1003. (!cdr ,l2)))
  1004. (nreverse ,r))))
  1005. (defun -zip-with (fn list1 list2)
  1006. "Zip the two lists LIST1 and LIST2 using a function FN. This
  1007. function is applied pairwise taking as first argument element of
  1008. LIST1 and as second argument element of LIST2 at corresponding
  1009. position.
  1010. The anaphoric form `--zip-with' binds the elements from LIST1 as symbol `it',
  1011. and the elements from LIST2 as symbol `other'."
  1012. (--zip-with (funcall fn it other) list1 list2))
  1013. (defun -zip-lists (&rest lists)
  1014. "Zip LISTS together. Group the head of each list, followed by the
  1015. second elements of each list, and so on. The lengths of the returned
  1016. groupings are equal to the length of the shortest input list.
  1017. The return value is always list of lists, which is a difference
  1018. from `-zip-pair' which returns a cons-cell in case two input
  1019. lists are provided.
  1020. See also: `-zip'"
  1021. (declare (pure t) (side-effect-free t))
  1022. (when lists
  1023. (let (results)
  1024. (while (-none? 'null lists)
  1025. (setq results (cons (mapcar 'car lists) results))
  1026. (setq lists (mapcar 'cdr lists)))
  1027. (nreverse results))))
  1028. (defun -zip (&rest lists)
  1029. "Zip LISTS together. Group the head of each list, followed by the
  1030. second elements of each list, and so on. The lengths of the returned
  1031. groupings are equal to the length of the shortest input list.
  1032. If two lists are provided as arguments, return the groupings as a list
  1033. of cons cells. Otherwise, return the groupings as a list of lists.
  1034. Use `-zip-lists' if you need the return value to always be a list
  1035. of lists.
  1036. Alias: `-zip-pair'
  1037. See also: `-zip-lists'"
  1038. (declare (pure t) (side-effect-free t))
  1039. (when lists
  1040. (let (results)
  1041. (while (-none? 'null lists)
  1042. (setq results (cons (mapcar 'car lists) results))
  1043. (setq lists (mapcar 'cdr lists)))
  1044. (setq results (nreverse results))
  1045. (if (= (length lists) 2)
  1046. ;; to support backward compatibility, return
  1047. ;; a cons cell if two lists were provided
  1048. (--map (cons (car it) (cadr it)) results)
  1049. results))))
  1050. (defalias '-zip-pair '-zip)
  1051. (defun -zip-fill (fill-value &rest lists)
  1052. "Zip LISTS, with FILL-VALUE padded onto the shorter lists. The
  1053. lengths of the returned groupings are equal to the length of the
  1054. longest input list."
  1055. (declare (pure t) (side-effect-free t))
  1056. (apply '-zip (apply '-pad (cons fill-value lists))))
  1057. (defun -unzip (lists)
  1058. "Unzip LISTS.
  1059. This works just like `-zip' but takes a list of lists instead of
  1060. a variable number of arguments, such that
  1061. (-unzip (-zip L1 L2 L3 ...))
  1062. is identity (given that the lists are the same length).
  1063. Note in particular that calling this on a list of two lists will
  1064. return a list of cons-cells such that the aboce identity works.
  1065. See also: `-zip'"
  1066. (apply '-zip lists))
  1067. (defun -cycle (list)
  1068. "Return an infinite copy of LIST that will cycle through the
  1069. elements and repeat from the beginning."
  1070. (declare (pure t) (side-effect-free t))
  1071. (let ((newlist (-map 'identity list)))
  1072. (nconc newlist newlist)))
  1073. (defun -pad (fill-value &rest lists)
  1074. "Appends FILL-VALUE to the end of each list in LISTS such that they
  1075. will all have the same length."
  1076. (let* ((annotations (-annotate 'length lists))
  1077. (n (-max (-map 'car annotations))))
  1078. (--map (append (cdr it) (-repeat (- n (car it)) fill-value)) annotations)))
  1079. (defun -annotate (fn list)
  1080. "Return a list of cons cells where each cell is FN applied to each
  1081. element of LIST paired with the unmodified element of LIST."
  1082. (-zip (-map fn list) list))
  1083. (defmacro --annotate (form list)
  1084. "Anaphoric version of `-annotate'."
  1085. (declare (debug (form form)))
  1086. `(-annotate (lambda (it) ,form) ,list))
  1087. (defun dash--table-carry (lists restore-lists &optional re)
  1088. "Helper for `-table' and `-table-flat'.
  1089. If a list overflows, carry to the right and reset the list."
  1090. (while (not (or (car lists)
  1091. (equal lists '(nil))))
  1092. (setcar lists (car restore-lists))
  1093. (pop (cadr lists))
  1094. (!cdr lists)
  1095. (!cdr restore-lists)
  1096. (when re
  1097. (push (nreverse (car re)) (cadr re))
  1098. (setcar re nil)
  1099. (!cdr re))))
  1100. (defun -table (fn &rest lists)
  1101. "Compute outer product of LISTS using function FN.
  1102. The function FN should have the same arity as the number of
  1103. supplied lists.
  1104. The outer product is computed by applying fn to all possible
  1105. combinations created by taking one element from each list in
  1106. order. The dimension of the result is (length lists).
  1107. See also: `-table-flat'"
  1108. (let ((restore-lists (copy-sequence lists))
  1109. (last-list (last lists))
  1110. (re (make-list (length lists) nil)))
  1111. (while (car last-list)
  1112. (let ((item (apply fn (-map 'car lists))))
  1113. (push item (car re))
  1114. (setcar lists (cdar lists)) ;; silence byte compiler
  1115. (dash--table-carry lists restore-lists re)))
  1116. (nreverse (car (last re)))))
  1117. (defun -table-flat (fn &rest lists)
  1118. "Compute flat outer product of LISTS using function FN.
  1119. The function FN should have the same arity as the number of
  1120. supplied lists.
  1121. The outer product is computed by applying fn to all possible
  1122. combinations created by taking one element from each list in
  1123. order. The results are flattened, ignoring the tensor structure
  1124. of the result. This is equivalent to calling:
  1125. (-flatten-n (1- (length lists)) (apply \\='-table fn lists))
  1126. but the implementation here is much more efficient.
  1127. See also: `-flatten-n', `-table'"
  1128. (let ((restore-lists (copy-sequence lists))
  1129. (last-list (last lists))
  1130. re)
  1131. (while (car last-list)
  1132. (let ((item (apply fn (-map 'car lists))))
  1133. (push item re)
  1134. (setcar lists (cdar lists)) ;; silence byte compiler
  1135. (dash--table-carry lists restore-lists)))
  1136. (nreverse re)))
  1137. (defun -partial (fn &rest args)
  1138. "Take a function FN and fewer than the normal arguments to FN,
  1139. and return a fn that takes a variable number of additional ARGS.
  1140. When called, the returned function calls FN with ARGS first and
  1141. then additional args."
  1142. (apply 'apply-partially fn args))
  1143. (defun -elem-index (elem list)
  1144. "Return the index of the first element in the given LIST which
  1145. is equal to the query element ELEM, or nil if there is no
  1146. such element."
  1147. (declare (pure t) (side-effect-free t))
  1148. (car (-elem-indices elem list)))
  1149. (defun -elem-indices (elem list)
  1150. "Return the indices of all elements in LIST equal to the query
  1151. element ELEM, in ascending order."
  1152. (declare (pure t) (side-effect-free t))
  1153. (-find-indices (-partial 'equal elem) list))
  1154. (defun -find-indices (pred list)
  1155. "Return the indices of all elements in LIST satisfying the
  1156. predicate PRED, in ascending order."
  1157. (apply 'append (--map-indexed (when (funcall pred it) (list it-index)) list)))
  1158. (defmacro --find-indices (form list)
  1159. "Anaphoric version of `-find-indices'."
  1160. (declare (debug (form form)))
  1161. `(-find-indices (lambda (it) ,form) ,list))
  1162. (defun -find-index (pred list)
  1163. "Take a predicate PRED and a LIST and return the index of the
  1164. first element in the list satisfying the predicate, or nil if
  1165. there is no such element.
  1166. See also `-first'."
  1167. (car (-find-indices pred list)))
  1168. (defmacro --find-index (form list)
  1169. "Anaphoric version of `-find-index'."
  1170. (declare (debug (form form)))
  1171. `(-find-index (lambda (it) ,form) ,list))
  1172. (defun -find-last-index (pred list)
  1173. "Take a predicate PRED and a LIST and return the index of the
  1174. last element in the list satisfying the predicate, or nil if
  1175. there is no such element.
  1176. See also `-last'."
  1177. (-last-item (-find-indices pred list)))
  1178. (defmacro --find-last-index (form list)
  1179. "Anaphoric version of `-find-last-index'."
  1180. `(-find-last-index (lambda (it) ,form) ,list))
  1181. (defun -select-by-indices (indices list)
  1182. "Return a list whose elements are elements from LIST selected
  1183. as `(nth i list)` for all i from INDICES."
  1184. (declare (pure t) (side-effect-free t))
  1185. (let (r)
  1186. (--each indices
  1187. (!cons (nth it list) r))
  1188. (nreverse r)))
  1189. (defun -select-columns (columns table)
  1190. "Select COLUMNS from TABLE.
  1191. TABLE is a list of lists where each element represents one row.
  1192. It is assumed each row has the same length.
  1193. Each row is transformed such that only the specified COLUMNS are
  1194. selected.
  1195. See also: `-select-column', `-select-by-indices'"
  1196. (declare (pure t) (side-effect-free t))
  1197. (--map (-select-by-indices columns it) table))
  1198. (defun -select-column (column table)
  1199. "Select COLUMN from TABLE.
  1200. TABLE is a list of lists where each element represents one row.
  1201. It is assumed each row has the same length.
  1202. The single selected column is returned as a list.
  1203. See also: `-select-columns', `-select-by-indices'"
  1204. (declare (pure t) (side-effect-free t))
  1205. (--mapcat (-select-by-indices (list column) it) table))
  1206. (defmacro -> (x &optional form &rest more)
  1207. "Thread the expr through the forms. Insert X as the second item
  1208. in the first form, making a list of it if it is not a list
  1209. already. If there are more forms, insert the first form as the
  1210. second item in second form, etc."
  1211. (declare (debug (form &rest [&or symbolp (sexp &rest form)])))
  1212. (cond
  1213. ((null form) x)
  1214. ((null more) (if (listp form)
  1215. `(,(car form) ,x ,@(cdr form))
  1216. (list form x)))
  1217. (:else `(-> (-> ,x ,form) ,@more))))
  1218. (defmacro ->> (x &optional form &rest more)
  1219. "Thread the expr through the forms. Insert X as the last item
  1220. in the first form, making a list of it if it is not a list
  1221. already. If there are more forms, insert the first form as the
  1222. last item in second form, etc."
  1223. (declare (debug ->))
  1224. (cond
  1225. ((null form) x)
  1226. ((null more) (if (listp form)
  1227. `(,@form ,x)
  1228. (list form x)))
  1229. (:else `(->> (->> ,x ,form) ,@more))))
  1230. (defmacro --> (x &rest forms)
  1231. "Starting with the value of X, thread each expression through FORMS.
  1232. Insert X at the position signified by the symbol `it' in the first
  1233. form. If there are more forms, insert the first form at the position
  1234. signified by `it' in in second form, etc."
  1235. (declare (debug (form body)))
  1236. `(-as-> ,x it ,@forms))
  1237. (defmacro -as-> (value variable &rest forms)
  1238. "Starting with VALUE, thread VARIABLE through FORMS.
  1239. In the first form, bind VARIABLE to VALUE. In the second form, bind
  1240. VARIABLE to the result of the first form, and so forth."
  1241. (declare (debug (form symbolp body)))
  1242. (if (null forms)
  1243. `,value
  1244. `(let ((,variable ,value))
  1245. (-as-> ,(if (symbolp (car forms))
  1246. (list (car forms) variable)
  1247. (car forms))
  1248. ,variable
  1249. ,@(cdr forms)))))
  1250. (defmacro -some-> (x &optional form &rest more)
  1251. "When expr is non-nil, thread it through the first form (via `->'),
  1252. and when that result is non-nil, through the next form, etc."
  1253. (declare (debug ->)
  1254. (indent 1))
  1255. (if (null form) x
  1256. (let ((result (make-symbol "result")))
  1257. `(-some-> (-when-let (,result ,x)
  1258. (-> ,result ,form))
  1259. ,@more))))
  1260. (defmacro -some->> (x &optional form &rest more)
  1261. "When expr is non-nil, thread it through the first form (via `->>'),
  1262. and when that result is non-nil, through the next form, etc."
  1263. (declare (debug ->)
  1264. (indent 1))
  1265. (if (null form) x
  1266. (let ((result (make-symbol "result")))
  1267. `(-some->> (-when-let (,result ,x)
  1268. (->> ,result ,form))
  1269. ,@more))))
  1270. (defmacro -some--> (x &optional form &rest more)
  1271. "When expr in non-nil, thread it through the first form (via `-->'),
  1272. and when that result is non-nil, through the next form, etc."
  1273. (declare (debug ->)
  1274. (indent 1))
  1275. (if (null form) x
  1276. (let ((result (make-symbol "result")))
  1277. `(-some--> (-when-let (,result ,x)
  1278. (--> ,result ,form))
  1279. ,@more))))
  1280. (defun -grade-up (comparator list)
  1281. "Grade elements of LIST using COMPARATOR relation, yielding a
  1282. permutation vector such that applying this permutation to LIST
  1283. sorts it in ascending order."
  1284. ;; ugly hack to "fix" lack of lexical scope
  1285. (let ((comp `(lambda (it other) (funcall ',comparator (car it) (car other)))))
  1286. (->> (--map-indexed (cons it it-index) list)
  1287. (-sort comp)
  1288. (-map 'cdr))))
  1289. (defun -grade-down (comparator list)
  1290. "Grade elements of LIST using COMPARATOR relation, yielding a
  1291. permutation vector such that applying this permutation to LIST
  1292. sorts it in descending order."
  1293. ;; ugly hack to "fix" lack of lexical scope
  1294. (let ((comp `(lambda (it other) (funcall ',comparator (car other) (car it)))))
  1295. (->> (--map-indexed (cons it it-index) list)
  1296. (-sort comp)
  1297. (-map 'cdr))))
  1298. (defvar dash--source-counter 0
  1299. "Monotonic counter for generated symbols.")
  1300. (defun dash--match-make-source-symbol ()
  1301. "Generate a new dash-source symbol.
  1302. All returned symbols are guaranteed to be unique."
  1303. (prog1 (make-symbol (format "--dash-source-%d--" dash--source-counter))
  1304. (setq dash--source-counter (1+ dash--source-counter))))
  1305. (defun dash--match-ignore-place-p (symbol)
  1306. "Return non-nil if SYMBOL is a symbol and starts with _."
  1307. (and (symbolp symbol)
  1308. (eq (aref (symbol-name symbol) 0) ?_)))
  1309. (defun dash--match-cons-skip-cdr (skip-cdr source)
  1310. "Helper function generating idiomatic shifting code."
  1311. (cond
  1312. ((= skip-cdr 0)
  1313. `(pop ,source))
  1314. (t
  1315. `(prog1 ,(dash--match-cons-get-car skip-cdr source)
  1316. (setq ,source ,(dash--match-cons-get-cdr (1+ skip-cdr) source))))))
  1317. (defun dash--match-cons-get-car (skip-cdr source)
  1318. "Helper function generating idiomatic code to get nth car."
  1319. (cond
  1320. ((= skip-cdr 0)
  1321. `(car ,source))
  1322. ((= skip-cdr 1)
  1323. `(cadr ,source))
  1324. (t
  1325. `(nth ,skip-cdr ,source))))
  1326. (defun dash--match-cons-get-cdr (skip-cdr source)
  1327. "Helper function generating idiomatic code to get nth cdr."
  1328. (cond
  1329. ((= skip-cdr 0)
  1330. source)
  1331. ((= skip-cdr 1)
  1332. `(cdr ,source))
  1333. (t
  1334. `(nthcdr ,skip-cdr ,source))))
  1335. (defun dash--match-cons (match-form source)
  1336. "Setup a cons matching environment and call the real matcher."
  1337. (let ((s (dash--match-make-source-symbol))
  1338. (n 0)
  1339. (m match-form))
  1340. (while (and (consp m)
  1341. (dash--match-ignore-place-p (car m)))
  1342. (setq n (1+ n)) (!cdr m))
  1343. (cond
  1344. ;; when we only have one pattern in the list, we don't have to
  1345. ;; create a temporary binding (--dash-source--) for the source
  1346. ;; and just use the input directly
  1347. ((and (consp m)
  1348. (not (cdr m)))
  1349. (dash--match (car m) (dash--match-cons-get-car n source)))
  1350. ;; handle other special types
  1351. ((> n 0)
  1352. (dash--match m (dash--match-cons-get-cdr n source)))
  1353. ;; this is the only entry-point for dash--match-cons-1, that's
  1354. ;; why we can't simply use the above branch, it would produce
  1355. ;; infinite recursion
  1356. (t
  1357. (cons (list s source) (dash--match-cons-1 match-form s))))))
  1358. (defun dash--get-expand-function (type)
  1359. "Get expand function name for TYPE."
  1360. (intern-soft (format "dash-expand:%s" type)))
  1361. (defun dash--match-cons-1 (match-form source &optional props)
  1362. "Match MATCH-FORM against SOURCE.
  1363. MATCH-FORM is a proper or improper list. Each element of
  1364. MATCH-FORM is either a symbol, which gets bound to the respective
  1365. value in source or another match form which gets destructured
  1366. recursively.
  1367. If the cdr of last cons cell in the list is `nil', matching stops
  1368. there.
  1369. SOURCE is a proper or improper list."
  1370. (let ((skip-cdr (or (plist-get props :skip-cdr) 0)))
  1371. (cond
  1372. ((consp match-form)
  1373. (cond
  1374. ((cdr match-form)
  1375. (cond
  1376. ((and (symbolp (car match-form))
  1377. (functionp (dash--get-expand-function (car match-form))))
  1378. (dash--match-kv (dash--match-kv-normalize-match-form match-form) (dash--match-cons-get-cdr skip-cdr source)))
  1379. ((dash--match-ignore-place-p (car match-form))
  1380. (dash--match-cons-1 (cdr match-form) source
  1381. (plist-put props :skip-cdr (1+ skip-cdr))))
  1382. (t
  1383. (-concat (dash--match (car match-form) (dash--match-cons-skip-cdr skip-cdr source))
  1384. (dash--match-cons-1 (cdr match-form) source)))))
  1385. (t ;; Last matching place, no need for shift
  1386. (dash--match (car match-form) (dash--match-cons-get-car skip-cdr source)))))
  1387. ((eq match-form nil)
  1388. nil)
  1389. (t ;; Handle improper lists. Last matching place, no need for shift
  1390. (dash--match match-form (dash--match-cons-get-cdr skip-cdr source))))))
  1391. (defun dash--vector-tail (seq start)
  1392. "Return the tail of SEQ starting at START."
  1393. (cond
  1394. ((vectorp seq)
  1395. (let* ((re-length (- (length seq) start))
  1396. (re (make-vector re-length 0)))
  1397. (--dotimes re-length (aset re it (aref seq (+ it start))))
  1398. re))
  1399. ((stringp seq)
  1400. (substring seq start))))
  1401. (defun dash--match-vector (match-form source)
  1402. "Setup a vector matching environment and call the real matcher."
  1403. (let ((s (dash--match-make-source-symbol)))
  1404. (cond
  1405. ;; don't bind `s' if we only have one sub-pattern
  1406. ((= (length match-form) 1)
  1407. (dash--match (aref match-form 0) `(aref ,source 0)))
  1408. ;; if the source is a symbol, we don't need to re-bind it
  1409. ((symbolp source)
  1410. (dash--match-vector-1 match-form source))
  1411. ;; don't bind `s' if we only have one sub-pattern which is not ignored
  1412. ((let* ((ignored-places (mapcar 'dash--match-ignore-place-p match-form))
  1413. (ignored-places-n (length (-remove 'null ignored-places))))
  1414. (when (= ignored-places-n (1- (length match-form)))
  1415. (let ((n (-find-index 'null ignored-places)))
  1416. (dash--match (aref match-form n) `(aref ,source ,n))))))
  1417. (t
  1418. (cons (list s source) (dash--match-vector-1 match-form s))))))
  1419. (defun dash--match-vector-1 (match-form source)
  1420. "Match MATCH-FORM against SOURCE.
  1421. MATCH-FORM is a vector. Each element of MATCH-FORM is either a
  1422. symbol, which gets bound to the respective value in source or
  1423. another match form which gets destructured recursively.
  1424. If second-from-last place in MATCH-FORM is the symbol &rest, the
  1425. next element of the MATCH-FORM is matched against the tail of
  1426. SOURCE, starting at index of the &rest symbol. This is
  1427. conceptually the same as the (head . tail) match for improper
  1428. lists, where dot plays the role of &rest.
  1429. SOURCE is a vector.
  1430. If the MATCH-FORM vector is shorter than SOURCE vector, only
  1431. the (length MATCH-FORM) places are bound, the rest of the SOURCE
  1432. is discarded."
  1433. (let ((i 0)
  1434. (l (length match-form))
  1435. (re))
  1436. (while (< i l)
  1437. (let ((m (aref match-form i)))
  1438. (push (cond
  1439. ((and (symbolp m)
  1440. (eq m '&rest))
  1441. (prog1 (dash--match
  1442. (aref match-form (1+ i))
  1443. `(dash--vector-tail ,source ,i))
  1444. (setq i l)))
  1445. ((and (symbolp m)
  1446. ;; do not match symbols starting with _
  1447. (not (eq (aref (symbol-name m) 0) ?_)))
  1448. (list (list m `(aref ,source ,i))))
  1449. ((not (symbolp m))
  1450. (dash--match m `(aref ,source ,i))))
  1451. re)
  1452. (setq i (1+ i))))
  1453. (-flatten-n 1 (nreverse re))))
  1454. (defun dash--match-kv-normalize-match-form (pattern)
  1455. "Normalize kv PATTERN.
  1456. This method normalizes PATTERN to the format expected by
  1457. `dash--match-kv'. See `-let' for the specification."
  1458. (let ((normalized (list (car pattern)))
  1459. (skip nil)
  1460. (fill-placeholder (make-symbol "--dash-fill-placeholder--")))
  1461. (-each (apply '-zip (-pad fill-placeholder (cdr pattern) (cddr pattern)))
  1462. (lambda (pair)
  1463. (let ((current (car pair))
  1464. (next (cdr pair)))
  1465. (if skip
  1466. (setq skip nil)
  1467. (if (or (eq fill-placeholder next)
  1468. (not (or (and (symbolp next)
  1469. (not (keywordp next))
  1470. (not (eq next t))
  1471. (not (eq next nil)))
  1472. (and (consp next)
  1473. (not (eq (car next) 'quote)))
  1474. (vectorp next))))
  1475. (progn
  1476. (cond
  1477. ((keywordp current)
  1478. (push current normalized)
  1479. (push (intern (substring (symbol-name current) 1)) normalized))
  1480. ((stringp current)
  1481. (push current normalized)
  1482. (push (intern current) normalized))
  1483. ((and (consp current)
  1484. (eq (car current) 'quote))
  1485. (push current normalized)
  1486. (push (cadr current) normalized))
  1487. (t (error "-let: found key `%s' in kv destructuring but its pattern `%s' is invalid and can not be derived from the key" current next)))
  1488. (setq skip nil))
  1489. (push current normalized)
  1490. (push next normalized)
  1491. (setq skip t))))))
  1492. (nreverse normalized)))
  1493. (defun dash--match-kv (match-form source)
  1494. "Setup a kv matching environment and call the real matcher.
  1495. kv can be any key-value store, such as plist, alist or hash-table."
  1496. (let ((s (dash--match-make-source-symbol)))
  1497. (cond
  1498. ;; don't bind `s' if we only have one sub-pattern (&type key val)
  1499. ((= (length match-form) 3)
  1500. (dash--match-kv-1 (cdr match-form) source (car match-form)))
  1501. ;; if the source is a symbol, we don't need to re-bind it
  1502. ((symbolp source)
  1503. (dash--match-kv-1 (cdr match-form) source (car match-form)))
  1504. (t
  1505. (cons (list s source) (dash--match-kv-1 (cdr match-form) s (car match-form)))))))
  1506. (defun dash-expand:&hash (key source)
  1507. "Generate extracting KEY from SOURCE for &hash destructuring."
  1508. `(gethash ,key ,source))
  1509. (defun dash-expand:&plist (key source)
  1510. "Generate extracting KEY from SOURCE for &plist destructuring."
  1511. `(plist-get ,source ,key))
  1512. (defun dash-expand:&alist (key source)
  1513. "Generate extracting KEY from SOURCE for &alist destructuring."
  1514. `(cdr (assoc ,key ,source)))
  1515. (defun dash-expand:&hash? (key source)
  1516. "Generate extracting KEY from SOURCE for &hash? destructuring.
  1517. Similar to &hash but check whether the map is not nil."
  1518. (let ((src (make-symbol "src")))
  1519. `(let ((,src ,source))
  1520. (when ,src (gethash ,key ,src)))))
  1521. (defalias 'dash-expand:&keys 'dash-expand:&plist)
  1522. (defun dash--match-kv-1 (match-form source type)
  1523. "Match MATCH-FORM against SOURCE of type TYPE.
  1524. MATCH-FORM is a proper list of the form (key1 place1 ... keyN
  1525. placeN). Each placeK is either a symbol, which gets bound to the
  1526. value of keyK retrieved from the key-value store, or another
  1527. match form which gets destructured recursively.
  1528. SOURCE is a key-value store of type TYPE, which can be a plist,
  1529. an alist or a hash table.
  1530. TYPE is a token specifying the type of the key-value store.
  1531. Valid values are &plist, &alist and &hash."
  1532. (-flatten-n 1 (-map
  1533. (lambda (kv)
  1534. (let* ((k (car kv))
  1535. (v (cadr kv))
  1536. (getter
  1537. (funcall (dash--get-expand-function type) k source)))
  1538. (cond
  1539. ((symbolp v)
  1540. (list (list v getter)))
  1541. (t (dash--match v getter)))))
  1542. (-partition 2 match-form))))
  1543. (defun dash--match-symbol (match-form source)
  1544. "Bind a symbol.
  1545. This works just like `let', there is no destructuring."
  1546. (list (list match-form source)))
  1547. (defun dash--match (match-form source)
  1548. "Match MATCH-FORM against SOURCE.
  1549. This function tests the MATCH-FORM and dispatches to specific
  1550. matchers based on the type of the expression.
  1551. Key-value stores are disambiguated by placing a token &plist,
  1552. &alist or &hash as a first item in the MATCH-FORM."
  1553. (cond
  1554. ((symbolp match-form)
  1555. (dash--match-symbol match-form source))
  1556. ((consp match-form)
  1557. (cond
  1558. ;; Handle the "x &as" bindings first.
  1559. ((and (consp (cdr match-form))
  1560. (symbolp (car match-form))
  1561. (eq '&as (cadr match-form)))
  1562. (let ((s (car match-form)))
  1563. (cons (list s source)
  1564. (dash--match (cddr match-form) s))))
  1565. ((functionp (dash--get-expand-function (car match-form)))
  1566. (dash--match-kv (dash--match-kv-normalize-match-form match-form) source))
  1567. (t (dash--match-cons match-form source))))
  1568. ((vectorp match-form)
  1569. ;; We support the &as binding in vectors too
  1570. (cond
  1571. ((and (> (length match-form) 2)
  1572. (symbolp (aref match-form 0))
  1573. (eq '&as (aref match-form 1)))
  1574. (let ((s (aref match-form 0)))
  1575. (cons (list s source)
  1576. (dash--match (dash--vector-tail match-form 2) s))))
  1577. (t (dash--match-vector match-form source))))))
  1578. (defun dash--normalize-let-varlist (varlist)
  1579. "Normalize VARLIST so that every binding is a list.
  1580. `let' allows specifying a binding which is not a list but simply
  1581. the place which is then automatically bound to nil, such that all
  1582. three of the following are identical and evaluate to nil.
  1583. (let (a) a)
  1584. (let ((a)) a)
  1585. (let ((a nil)) a)
  1586. This function normalizes all of these to the last form."
  1587. (--map (if (consp it) it (list it nil)) varlist))
  1588. (defmacro -let* (varlist &rest body)
  1589. "Bind variables according to VARLIST then eval BODY.
  1590. VARLIST is a list of lists of the form (PATTERN SOURCE). Each
  1591. PATTERN is matched against the SOURCE structurally. SOURCE is
  1592. only evaluated once for each PATTERN.
  1593. Each SOURCE can refer to the symbols already bound by this
  1594. VARLIST. This is useful if you want to destructure SOURCE
  1595. recursively but also want to name the intermediate structures.
  1596. See `-let' for the list of all possible patterns."
  1597. (declare (debug ((&rest [&or (sexp form) sexp]) body))
  1598. (indent 1))
  1599. (let* ((varlist (dash--normalize-let-varlist varlist))
  1600. (bindings (--mapcat (dash--match (car it) (cadr it)) varlist)))
  1601. `(let* ,bindings
  1602. ,@body)))
  1603. (defmacro -let (varlist &rest body)
  1604. "Bind variables according to VARLIST then eval BODY.
  1605. VARLIST is a list of lists of the form (PATTERN SOURCE). Each
  1606. PATTERN is matched against the SOURCE \"structurally\". SOURCE
  1607. is only evaluated once for each PATTERN. Each PATTERN is matched
  1608. recursively, and can therefore contain sub-patterns which are
  1609. matched against corresponding sub-expressions of SOURCE.
  1610. All the SOURCEs are evalled before any symbols are
  1611. bound (i.e. \"in parallel\").
  1612. If VARLIST only contains one (PATTERN SOURCE) element, you can
  1613. optionally specify it using a vector and discarding the
  1614. outer-most parens. Thus
  1615. (-let ((PATTERN SOURCE)) ..)
  1616. becomes
  1617. (-let [PATTERN SOURCE] ..).
  1618. `-let' uses a convention of not binding places (symbols) starting
  1619. with _ whenever it's possible. You can use this to skip over
  1620. entries you don't care about. However, this is not *always*
  1621. possible (as a result of implementation) and these symbols might
  1622. get bound to undefined values.
  1623. Following is the overview of supported patterns. Remember that
  1624. patterns can be matched recursively, so every a, b, aK in the
  1625. following can be a matching construct and not necessarily a
  1626. symbol/variable.
  1627. Symbol:
  1628. a - bind the SOURCE to A. This is just like regular `let'.
  1629. Conses and lists:
  1630. (a) - bind `car' of cons/list to A
  1631. (a . b) - bind car of cons to A and `cdr' to B
  1632. (a b) - bind car of list to A and `cadr' to B
  1633. (a1 a2 a3 ...) - bind 0th car of list to A1, 1st to A2, 2nd to A3 ...
  1634. (a1 a2 a3 ... aN . rest) - as above, but bind the Nth cdr to REST.
  1635. Vectors:
  1636. [a] - bind 0th element of a non-list sequence to A (works with
  1637. vectors, strings, bit arrays...)
  1638. [a1 a2 a3 ...] - bind 0th element of non-list sequence to A0, 1st to
  1639. A1, 2nd to A2, ...
  1640. If the PATTERN is shorter than SOURCE, the values at
  1641. places not in PATTERN are ignored.
  1642. If the PATTERN is longer than SOURCE, an `error' is
  1643. thrown.
  1644. [a1 a2 a3 ... &rest rest] - as above, but bind the rest of
  1645. the sequence to REST. This is
  1646. conceptually the same as improper list
  1647. matching (a1 a2 ... aN . rest)
  1648. Key/value stores:
  1649. (&plist key0 a0 ... keyN aN) - bind value mapped by keyK in the
  1650. SOURCE plist to aK. If the
  1651. value is not found, aK is nil.
  1652. Uses `plist-get' to fetch values.
  1653. (&alist key0 a0 ... keyN aN) - bind value mapped by keyK in the
  1654. SOURCE alist to aK. If the
  1655. value is not found, aK is nil.
  1656. Uses `assoc' to fetch values.
  1657. (&hash key0 a0 ... keyN aN) - bind value mapped by keyK in the
  1658. SOURCE hash table to aK. If the
  1659. value is not found, aK is nil.
  1660. Uses `gethash' to fetch values.
  1661. Further, special keyword &keys supports \"inline\" matching of
  1662. plist-like key-value pairs, similarly to &keys keyword of
  1663. `cl-defun'.
  1664. (a1 a2 ... aN &keys key1 b1 ... keyN bK)
  1665. This binds N values from the list to a1 ... aN, then interprets
  1666. the cdr as a plist (see key/value matching above).
  1667. A shorthand notation for kv-destructuring exists which allows the
  1668. patterns be optionally left out and derived from the key name in
  1669. the following fashion:
  1670. - a key :foo is converted into `foo' pattern,
  1671. - a key 'bar is converted into `bar' pattern,
  1672. - a key \"baz\" is converted into `baz' pattern.
  1673. That is, the entire value under the key is bound to the derived
  1674. variable without any further destructuring.
  1675. This is possible only when the form following the key is not a
  1676. valid pattern (i.e. not a symbol, a cons cell or a vector).
  1677. Otherwise the matching proceeds as usual and in case of an
  1678. invalid spec fails with an error.
  1679. Thus the patterns are normalized as follows:
  1680. ;; derive all the missing patterns
  1681. (&plist :foo 'bar \"baz\") => (&plist :foo foo 'bar bar \"baz\" baz)
  1682. ;; we can specify some but not others
  1683. (&plist :foo 'bar explicit-bar) => (&plist :foo foo 'bar explicit-bar)
  1684. ;; nothing happens, we store :foo in x
  1685. (&plist :foo x) => (&plist :foo x)
  1686. ;; nothing happens, we match recursively
  1687. (&plist :foo (a b c)) => (&plist :foo (a b c))
  1688. You can name the source using the syntax SYMBOL &as PATTERN.
  1689. This syntax works with lists (proper or improper), vectors and
  1690. all types of maps.
  1691. (list &as a b c) (list 1 2 3)
  1692. binds A to 1, B to 2, C to 3 and LIST to (1 2 3).
  1693. Similarly:
  1694. (bounds &as beg . end) (cons 1 2)
  1695. binds BEG to 1, END to 2 and BOUNDS to (1 . 2).
  1696. (items &as first . rest) (list 1 2 3)
  1697. binds FIRST to 1, REST to (2 3) and ITEMS to (1 2 3)
  1698. [vect &as _ b c] [1 2 3]
  1699. binds B to 2, C to 3 and VECT to [1 2 3] (_ avoids binding as usual).
  1700. (plist &as &plist :b b) (list :a 1 :b 2 :c 3)
  1701. binds B to 2 and PLIST to (:a 1 :b 2 :c 3). Same for &alist and &hash.
  1702. This is especially useful when we want to capture the result of a
  1703. computation and destructure at the same time. Consider the
  1704. form (function-returning-complex-structure) returning a list of
  1705. two vectors with two items each. We want to capture this entire
  1706. result and pass it to another computation, but at the same time
  1707. we want to get the second item from each vector. We can achieve
  1708. it with pattern
  1709. (result &as [_ a] [_ b]) (function-returning-complex-structure)
  1710. Note: Clojure programmers may know this feature as the \":as
  1711. binding\". The difference is that we put the &as at the front
  1712. because we need to support improper list binding."
  1713. (declare (debug ([&or (&rest [&or (sexp form) sexp])
  1714. (vector [&rest [sexp form]])]
  1715. body))
  1716. (indent 1))
  1717. (if (vectorp varlist)
  1718. `(let* ,(dash--match (aref varlist 0) (aref varlist 1))
  1719. ,@body)
  1720. (let* ((varlist (dash--normalize-let-varlist varlist))
  1721. (inputs (--map-indexed (list (make-symbol (format "input%d" it-index)) (cadr it)) varlist))
  1722. (new-varlist (--map (list (caar it) (cadr it)) (-zip varlist inputs))))
  1723. `(let ,inputs
  1724. (-let* ,new-varlist ,@body)))))
  1725. (defmacro -lambda (match-form &rest body)
  1726. "Return a lambda which destructures its input as MATCH-FORM and executes BODY.
  1727. Note that you have to enclose the MATCH-FORM in a pair of parens,
  1728. such that:
  1729. (-lambda (x) body)
  1730. (-lambda (x y ...) body)
  1731. has the usual semantics of `lambda'. Furthermore, these get
  1732. translated into normal lambda, so there is no performance
  1733. penalty.
  1734. See `-let' for the description of destructuring mechanism."
  1735. (declare (doc-string 2) (indent defun)
  1736. (debug (&define sexp
  1737. [&optional stringp]
  1738. [&optional ("interactive" interactive)]
  1739. def-body)))
  1740. (cond
  1741. ((not (consp match-form))
  1742. (signal 'wrong-type-argument "match-form must be a list"))
  1743. ;; no destructuring, so just return regular lambda to make things faster
  1744. ((-all? 'symbolp match-form)
  1745. `(lambda ,match-form ,@body))
  1746. (t
  1747. (let* ((inputs (--map-indexed (list it (make-symbol (format "input%d" it-index))) match-form)))
  1748. ;; TODO: because inputs to the lambda are evaluated only once,
  1749. ;; -let* need not to create the extra bindings to ensure that.
  1750. ;; We should find a way to optimize that. Not critical however.
  1751. `(lambda ,(--map (cadr it) inputs)
  1752. (-let* ,inputs ,@body))))))
  1753. (defmacro -setq (&rest forms)
  1754. "Bind each MATCH-FORM to the value of its VAL.
  1755. MATCH-FORM destructuring is done according to the rules of `-let'.
  1756. This macro allows you to bind multiple variables by destructuring
  1757. the value, so for example:
  1758. (-setq (a b) x
  1759. (&plist :c c) plist)
  1760. expands roughly speaking to the following code
  1761. (setq a (car x)
  1762. b (cadr x)
  1763. c (plist-get plist :c))
  1764. Care is taken to only evaluate each VAL once so that in case of
  1765. multiple assignments it does not cause unexpected side effects.
  1766. \(fn [MATCH-FORM VAL]...)"
  1767. (declare (debug (&rest sexp form))
  1768. (indent 1))
  1769. (when (= (mod (length forms) 2) 1)
  1770. (error "Odd number of arguments"))
  1771. (let* ((forms-and-sources
  1772. ;; First get all the necessary mappings with all the
  1773. ;; intermediate bindings.
  1774. (-map (lambda (x) (dash--match (car x) (cadr x)))
  1775. (-partition 2 forms)))
  1776. ;; To preserve the logic of dynamic scoping we must ensure
  1777. ;; that we `setq' the variables outside of the `let*' form
  1778. ;; which holds the destructured intermediate values. For
  1779. ;; this we generate for each variable a placeholder which is
  1780. ;; bound to (lexically) the result of the destructuring.
  1781. ;; Then outside of the helper `let*' form we bind all the
  1782. ;; original variables to their respective placeholders.
  1783. ;; TODO: There is a lot of room for possible optimization,
  1784. ;; for start playing with `special-variable-p' to eliminate
  1785. ;; unnecessary re-binding.
  1786. (variables-to-placeholders
  1787. (-mapcat
  1788. (lambda (bindings)
  1789. (-map
  1790. (lambda (binding)
  1791. (let ((var (car binding)))
  1792. (list var (make-symbol (concat "--dash-binding-" (symbol-name var) "--")))))
  1793. (--filter (not (string-prefix-p "--" (symbol-name (car it)))) bindings)))
  1794. forms-and-sources)))
  1795. `(let ,(-map 'cadr variables-to-placeholders)
  1796. (let* ,(-flatten-n 1 forms-and-sources)
  1797. (setq ,@(-flatten (-map 'reverse variables-to-placeholders))))
  1798. (setq ,@(-flatten variables-to-placeholders)))))
  1799. (defmacro -if-let* (vars-vals then &rest else)
  1800. "If all VALS evaluate to true, bind them to their corresponding
  1801. VARS and do THEN, otherwise do ELSE. VARS-VALS should be a list
  1802. of (VAR VAL) pairs.
  1803. Note: binding is done according to `-let*'. VALS are evaluated
  1804. sequentially, and evaluation stops after the first nil VAL is
  1805. encountered."
  1806. (declare (debug ((&rest (sexp form)) form body))
  1807. (indent 2))
  1808. (->> vars-vals
  1809. (--mapcat (dash--match (car it) (cadr it)))
  1810. (--reduce-r-from
  1811. (let ((var (car it))
  1812. (val (cadr it)))
  1813. `(let ((,var ,val))
  1814. (if ,var ,acc ,@else)))
  1815. then)))
  1816. (defmacro -if-let (var-val then &rest else)
  1817. "If VAL evaluates to non-nil, bind it to VAR and do THEN,
  1818. otherwise do ELSE.
  1819. Note: binding is done according to `-let'.
  1820. \(fn (VAR VAL) THEN &rest ELSE)"
  1821. (declare (debug ((sexp form) form body))
  1822. (indent 2))
  1823. `(-if-let* (,var-val) ,then ,@else))
  1824. (defmacro --if-let (val then &rest else)
  1825. "If VAL evaluates to non-nil, bind it to symbol `it' and do THEN,
  1826. otherwise do ELSE."
  1827. (declare (debug (form form body))
  1828. (indent 2))
  1829. `(-if-let (it ,val) ,then ,@else))
  1830. (defmacro -when-let* (vars-vals &rest body)
  1831. "If all VALS evaluate to true, bind them to their corresponding
  1832. VARS and execute body. VARS-VALS should be a list of (VAR VAL)
  1833. pairs.
  1834. Note: binding is done according to `-let*'. VALS are evaluated
  1835. sequentially, and evaluation stops after the first nil VAL is
  1836. encountered."
  1837. (declare (debug ((&rest (sexp form)) body))
  1838. (indent 1))
  1839. `(-if-let* ,vars-vals (progn ,@body)))
  1840. (defmacro -when-let (var-val &rest body)
  1841. "If VAL evaluates to non-nil, bind it to VAR and execute body.
  1842. Note: binding is done according to `-let'.
  1843. \(fn (VAR VAL) &rest BODY)"
  1844. (declare (debug ((sexp form) body))
  1845. (indent 1))
  1846. `(-if-let ,var-val (progn ,@body)))
  1847. (defmacro --when-let (val &rest body)
  1848. "If VAL evaluates to non-nil, bind it to symbol `it' and
  1849. execute body."
  1850. (declare (debug (form body))
  1851. (indent 1))
  1852. `(--if-let ,val (progn ,@body)))
  1853. (defvar -compare-fn nil
  1854. "Tests for equality use this function or `equal' if this is nil.
  1855. It should only be set using dynamic scope with a let, like:
  1856. (let ((-compare-fn #\\='=)) (-union numbers1 numbers2 numbers3)")
  1857. (defun -distinct (list)
  1858. "Return a new list with all duplicates removed.
  1859. The test for equality is done with `equal',
  1860. or with `-compare-fn' if that's non-nil.
  1861. Alias: `-uniq'"
  1862. ;; Implementation note: The speedup gained from hash table lookup
  1863. ;; starts to outweigh its overhead for lists of length greater than
  1864. ;; 32. See discussion in PR #305.
  1865. (let* ((len (length list))
  1866. (lut (and (> len 32)
  1867. ;; Check that `-compare-fn' is a valid hash-table
  1868. ;; lookup function or `nil'.
  1869. (memq -compare-fn '(nil equal eq eql))
  1870. (make-hash-table :test (or -compare-fn #'equal)
  1871. :size len))))
  1872. (if lut
  1873. (--filter (unless (gethash it lut)
  1874. (puthash it t lut))
  1875. list)
  1876. (--each list (unless (-contains? lut it) (!cons it lut)))
  1877. (nreverse lut))))
  1878. (defalias '-uniq '-distinct)
  1879. (defun -union (list list2)
  1880. "Return a new list containing the elements of LIST and elements of LIST2 that are not in LIST.
  1881. The test for equality is done with `equal',
  1882. or with `-compare-fn' if that's non-nil."
  1883. ;; We fall back to iteration implementation if the comparison
  1884. ;; function isn't one of `eq', `eql' or `equal'.
  1885. (let* ((result (reverse list))
  1886. ;; TODO: get rid of this dynamic variable, pass it as an
  1887. ;; argument instead.
  1888. (-compare-fn (if (bound-and-true-p -compare-fn)
  1889. -compare-fn
  1890. 'equal)))
  1891. (if (memq -compare-fn '(eq eql equal))
  1892. (let ((ht (make-hash-table :test -compare-fn)))
  1893. (--each list (puthash it t ht))
  1894. (--each list2 (unless (gethash it ht) (!cons it result))))
  1895. (--each list2 (unless (-contains? result it) (!cons it result))))
  1896. (nreverse result)))
  1897. (defun -intersection (list list2)
  1898. "Return a new list containing only the elements that are members of both LIST and LIST2.
  1899. The test for equality is done with `equal',
  1900. or with `-compare-fn' if that's non-nil."
  1901. (--filter (-contains? list2 it) list))
  1902. (defun -difference (list list2)
  1903. "Return a new list with only the members of LIST that are not in LIST2.
  1904. The test for equality is done with `equal',
  1905. or with `-compare-fn' if that's non-nil."
  1906. (--filter (not (-contains? list2 it)) list))
  1907. (defun -powerset (list)
  1908. "Return the power set of LIST."
  1909. (if (null list) '(())
  1910. (let ((last (-powerset (cdr list))))
  1911. (append (mapcar (lambda (x) (cons (car list) x)) last)
  1912. last))))
  1913. (defun -permutations (list)
  1914. "Return the permutations of LIST."
  1915. (if (null list) '(())
  1916. (apply #'append
  1917. (mapcar (lambda (x)
  1918. (mapcar (lambda (perm) (cons x perm))
  1919. (-permutations (remove x list))))
  1920. list))))
  1921. (defun -inits (list)
  1922. "Return all prefixes of LIST."
  1923. (let ((res (list list)))
  1924. (setq list (reverse list))
  1925. (while list
  1926. (push (reverse (!cdr list)) res))
  1927. res))
  1928. (defun -tails (list)
  1929. "Return all suffixes of LIST"
  1930. (-reductions-r-from 'cons nil list))
  1931. (defun -common-prefix (&rest lists)
  1932. "Return the longest common prefix of LISTS."
  1933. (declare (pure t) (side-effect-free t))
  1934. (--reduce (--take-while (and acc (equal (pop acc) it)) it)
  1935. lists))
  1936. (defun -common-suffix (&rest lists)
  1937. "Return the longest common suffix of LISTS."
  1938. (nreverse (apply #'-common-prefix (mapcar #'reverse lists))))
  1939. (defun -contains? (list element)
  1940. "Return non-nil if LIST contains ELEMENT.
  1941. The test for equality is done with `equal', or with `-compare-fn'
  1942. if that's non-nil.
  1943. Alias: `-contains-p'"
  1944. (not
  1945. (null
  1946. (cond
  1947. ((null -compare-fn) (member element list))
  1948. ((eq -compare-fn 'eq) (memq element list))
  1949. ((eq -compare-fn 'eql) (memql element list))
  1950. (t
  1951. (let ((lst list))
  1952. (while (and lst
  1953. (not (funcall -compare-fn element (car lst))))
  1954. (setq lst (cdr lst)))
  1955. lst))))))
  1956. (defalias '-contains-p '-contains?)
  1957. (defun -same-items? (list list2)
  1958. "Return true if LIST and LIST2 has the same items.
  1959. The order of the elements in the lists does not matter.
  1960. Alias: `-same-items-p'"
  1961. (let ((length-a (length list))
  1962. (length-b (length list2)))
  1963. (and
  1964. (= length-a length-b)
  1965. (= length-a (length (-intersection list list2))))))
  1966. (defalias '-same-items-p '-same-items?)
  1967. (defun -is-prefix? (prefix list)
  1968. "Return non-nil if PREFIX is prefix of LIST.
  1969. Alias: `-is-prefix-p'"
  1970. (declare (pure t) (side-effect-free t))
  1971. (--each-while list (equal (car prefix) it)
  1972. (!cdr prefix))
  1973. (not prefix))
  1974. (defun -is-suffix? (suffix list)
  1975. "Return non-nil if SUFFIX is suffix of LIST.
  1976. Alias: `-is-suffix-p'"
  1977. (declare (pure t) (side-effect-free t))
  1978. (-is-prefix? (reverse suffix) (reverse list)))
  1979. (defun -is-infix? (infix list)
  1980. "Return non-nil if INFIX is infix of LIST.
  1981. This operation runs in O(n^2) time
  1982. Alias: `-is-infix-p'"
  1983. (declare (pure t) (side-effect-free t))
  1984. (let (done)
  1985. (while (and (not done) list)
  1986. (setq done (-is-prefix? infix list))
  1987. (!cdr list))
  1988. done))
  1989. (defalias '-is-prefix-p '-is-prefix?)
  1990. (defalias '-is-suffix-p '-is-suffix?)
  1991. (defalias '-is-infix-p '-is-infix?)
  1992. (defun -sort (comparator list)
  1993. "Sort LIST, stably, comparing elements using COMPARATOR.
  1994. Return the sorted list. LIST is NOT modified by side effects.
  1995. COMPARATOR is called with two elements of LIST, and should return non-nil
  1996. if the first element should sort before the second."
  1997. (sort (copy-sequence list) comparator))
  1998. (defmacro --sort (form list)
  1999. "Anaphoric form of `-sort'."
  2000. (declare (debug (form form)))
  2001. `(-sort (lambda (it other) ,form) ,list))
  2002. (defun -list (&rest args)
  2003. "Return a list with ARGS.
  2004. If first item of ARGS is already a list, simply return ARGS. If
  2005. not, return a list with ARGS as elements."
  2006. (declare (pure t) (side-effect-free t))
  2007. (let ((arg (car args)))
  2008. (if (listp arg) arg args)))
  2009. (defun -repeat (n x)
  2010. "Return a list with X repeated N times.
  2011. Return nil if N is less than 1."
  2012. (declare (pure t) (side-effect-free t))
  2013. (let (ret)
  2014. (--dotimes n (!cons x ret))
  2015. ret))
  2016. (defun -sum (list)
  2017. "Return the sum of LIST."
  2018. (declare (pure t) (side-effect-free t))
  2019. (apply '+ list))
  2020. (defun -running-sum (list)
  2021. "Return a list with running sums of items in LIST.
  2022. LIST must be non-empty."
  2023. (declare (pure t) (side-effect-free t))
  2024. (unless (consp list)
  2025. (error "LIST must be non-empty"))
  2026. (-reductions '+ list))
  2027. (defun -product (list)
  2028. "Return the product of LIST."
  2029. (declare (pure t) (side-effect-free t))
  2030. (apply '* list))
  2031. (defun -running-product (list)
  2032. "Return a list with running products of items in LIST.
  2033. LIST must be non-empty."
  2034. (declare (pure t) (side-effect-free t))
  2035. (unless (consp list)
  2036. (error "LIST must be non-empty"))
  2037. (-reductions '* list))
  2038. (defun -max (list)
  2039. "Return the largest value from LIST of numbers or markers."
  2040. (declare (pure t) (side-effect-free t))
  2041. (apply 'max list))
  2042. (defun -min (list)
  2043. "Return the smallest value from LIST of numbers or markers."
  2044. (declare (pure t) (side-effect-free t))
  2045. (apply 'min list))
  2046. (defun -max-by (comparator list)
  2047. "Take a comparison function COMPARATOR and a LIST and return
  2048. the greatest element of the list by the comparison function.
  2049. See also combinator `-on' which can transform the values before
  2050. comparing them."
  2051. (--reduce (if (funcall comparator it acc) it acc) list))
  2052. (defun -min-by (comparator list)
  2053. "Take a comparison function COMPARATOR and a LIST and return
  2054. the least element of the list by the comparison function.
  2055. See also combinator `-on' which can transform the values before
  2056. comparing them."
  2057. (--reduce (if (funcall comparator it acc) acc it) list))
  2058. (defmacro --max-by (form list)
  2059. "Anaphoric version of `-max-by'.
  2060. The items for the comparator form are exposed as \"it\" and \"other\"."
  2061. (declare (debug (form form)))
  2062. `(-max-by (lambda (it other) ,form) ,list))
  2063. (defmacro --min-by (form list)
  2064. "Anaphoric version of `-min-by'.
  2065. The items for the comparator form are exposed as \"it\" and \"other\"."
  2066. (declare (debug (form form)))
  2067. `(-min-by (lambda (it other) ,form) ,list))
  2068. (defun -iterate (fun init n)
  2069. "Return a list of iterated applications of FUN to INIT.
  2070. This means a list of form:
  2071. (init (fun init) (fun (fun init)) ...)
  2072. N is the length of the returned list."
  2073. (if (= n 0) nil
  2074. (let ((r (list init)))
  2075. (--dotimes (1- n)
  2076. (push (funcall fun (car r)) r))
  2077. (nreverse r))))
  2078. (defun -fix (fn list)
  2079. "Compute the (least) fixpoint of FN with initial input LIST.
  2080. FN is called at least once, results are compared with `equal'."
  2081. (let ((re (funcall fn list)))
  2082. (while (not (equal list re))
  2083. (setq list re)
  2084. (setq re (funcall fn re)))
  2085. re))
  2086. (defmacro --fix (form list)
  2087. "Anaphoric form of `-fix'."
  2088. `(-fix (lambda (it) ,form) ,list))
  2089. (defun -unfold (fun seed)
  2090. "Build a list from SEED using FUN.
  2091. This is \"dual\" operation to `-reduce-r': while -reduce-r
  2092. consumes a list to produce a single value, `-unfold' takes a
  2093. seed value and builds a (potentially infinite!) list.
  2094. FUN should return `nil' to stop the generating process, or a
  2095. cons (A . B), where A will be prepended to the result and B is
  2096. the new seed."
  2097. (let ((last (funcall fun seed)) r)
  2098. (while last
  2099. (push (car last) r)
  2100. (setq last (funcall fun (cdr last))))
  2101. (nreverse r)))
  2102. (defmacro --unfold (form seed)
  2103. "Anaphoric version of `-unfold'."
  2104. (declare (debug (form form)))
  2105. `(-unfold (lambda (it) ,form) ,seed))
  2106. (defun -cons-pair? (con)
  2107. "Return non-nil if CON is true cons pair.
  2108. That is (A . B) where B is not a list.
  2109. Alias: `-cons-pair-p'"
  2110. (declare (pure t) (side-effect-free t))
  2111. (and (listp con)
  2112. (not (listp (cdr con)))))
  2113. (defalias '-cons-pair-p '-cons-pair?)
  2114. (defun -cons-to-list (con)
  2115. "Convert a cons pair to a list with `car' and `cdr' of the pair respectively."
  2116. (declare (pure t) (side-effect-free t))
  2117. (list (car con) (cdr con)))
  2118. (defun -value-to-list (val)
  2119. "Convert a value to a list.
  2120. If the value is a cons pair, make a list with two elements, `car'
  2121. and `cdr' of the pair respectively.
  2122. If the value is anything else, wrap it in a list."
  2123. (declare (pure t) (side-effect-free t))
  2124. (cond
  2125. ((-cons-pair? val) (-cons-to-list val))
  2126. (t (list val))))
  2127. (defun -tree-mapreduce-from (fn folder init-value tree)
  2128. "Apply FN to each element of TREE, and make a list of the results.
  2129. If elements of TREE are lists themselves, apply FN recursively to
  2130. elements of these nested lists.
  2131. Then reduce the resulting lists using FOLDER and initial value
  2132. INIT-VALUE. See `-reduce-r-from'.
  2133. This is the same as calling `-tree-reduce-from' after `-tree-map'
  2134. but is twice as fast as it only traverse the structure once."
  2135. (cond
  2136. ((not tree) nil)
  2137. ((-cons-pair? tree) (funcall fn tree))
  2138. ((listp tree)
  2139. (-reduce-r-from folder init-value (mapcar (lambda (x) (-tree-mapreduce-from fn folder init-value x)) tree)))
  2140. (t (funcall fn tree))))
  2141. (defmacro --tree-mapreduce-from (form folder init-value tree)
  2142. "Anaphoric form of `-tree-mapreduce-from'."
  2143. (declare (debug (form form form form)))
  2144. `(-tree-mapreduce-from (lambda (it) ,form) (lambda (it acc) ,folder) ,init-value ,tree))
  2145. (defun -tree-mapreduce (fn folder tree)
  2146. "Apply FN to each element of TREE, and make a list of the results.
  2147. If elements of TREE are lists themselves, apply FN recursively to
  2148. elements of these nested lists.
  2149. Then reduce the resulting lists using FOLDER and initial value
  2150. INIT-VALUE. See `-reduce-r-from'.
  2151. This is the same as calling `-tree-reduce' after `-tree-map'
  2152. but is twice as fast as it only traverse the structure once."
  2153. (cond
  2154. ((not tree) nil)
  2155. ((-cons-pair? tree) (funcall fn tree))
  2156. ((listp tree)
  2157. (-reduce-r folder (mapcar (lambda (x) (-tree-mapreduce fn folder x)) tree)))
  2158. (t (funcall fn tree))))
  2159. (defmacro --tree-mapreduce (form folder tree)
  2160. "Anaphoric form of `-tree-mapreduce'."
  2161. (declare (debug (form form form)))
  2162. `(-tree-mapreduce (lambda (it) ,form) (lambda (it acc) ,folder) ,tree))
  2163. (defun -tree-map (fn tree)
  2164. "Apply FN to each element of TREE while preserving the tree structure."
  2165. (cond
  2166. ((not tree) nil)
  2167. ((-cons-pair? tree) (funcall fn tree))
  2168. ((listp tree)
  2169. (mapcar (lambda (x) (-tree-map fn x)) tree))
  2170. (t (funcall fn tree))))
  2171. (defmacro --tree-map (form tree)
  2172. "Anaphoric form of `-tree-map'."
  2173. (declare (debug (form form)))
  2174. `(-tree-map (lambda (it) ,form) ,tree))
  2175. (defun -tree-reduce-from (fn init-value tree)
  2176. "Use FN to reduce elements of list TREE.
  2177. If elements of TREE are lists themselves, apply the reduction recursively.
  2178. FN is first applied to INIT-VALUE and first element of the list,
  2179. then on this result and second element from the list etc.
  2180. The initial value is ignored on cons pairs as they always contain
  2181. two elements."
  2182. (cond
  2183. ((not tree) nil)
  2184. ((-cons-pair? tree) tree)
  2185. ((listp tree)
  2186. (-reduce-r-from fn init-value (mapcar (lambda (x) (-tree-reduce-from fn init-value x)) tree)))
  2187. (t tree)))
  2188. (defmacro --tree-reduce-from (form init-value tree)
  2189. "Anaphoric form of `-tree-reduce-from'."
  2190. (declare (debug (form form form)))
  2191. `(-tree-reduce-from (lambda (it acc) ,form) ,init-value ,tree))
  2192. (defun -tree-reduce (fn tree)
  2193. "Use FN to reduce elements of list TREE.
  2194. If elements of TREE are lists themselves, apply the reduction recursively.
  2195. FN is first applied to first element of the list and second
  2196. element, then on this result and third element from the list etc.
  2197. See `-reduce-r' for how exactly are lists of zero or one element handled."
  2198. (cond
  2199. ((not tree) nil)
  2200. ((-cons-pair? tree) tree)
  2201. ((listp tree)
  2202. (-reduce-r fn (mapcar (lambda (x) (-tree-reduce fn x)) tree)))
  2203. (t tree)))
  2204. (defmacro --tree-reduce (form tree)
  2205. "Anaphoric form of `-tree-reduce'."
  2206. (declare (debug (form form)))
  2207. `(-tree-reduce (lambda (it acc) ,form) ,tree))
  2208. (defun -tree-map-nodes (pred fun tree)
  2209. "Call FUN on each node of TREE that satisfies PRED.
  2210. If PRED returns nil, continue descending down this node. If PRED
  2211. returns non-nil, apply FUN to this node and do not descend
  2212. further."
  2213. (if (funcall pred tree)
  2214. (funcall fun tree)
  2215. (if (and (listp tree)
  2216. (not (-cons-pair? tree)))
  2217. (-map (lambda (x) (-tree-map-nodes pred fun x)) tree)
  2218. tree)))
  2219. (defmacro --tree-map-nodes (pred form tree)
  2220. "Anaphoric form of `-tree-map-nodes'."
  2221. `(-tree-map-nodes (lambda (it) ,pred) (lambda (it) ,form) ,tree))
  2222. (defun -tree-seq (branch children tree)
  2223. "Return a sequence of the nodes in TREE, in depth-first search order.
  2224. BRANCH is a predicate of one argument that returns non-nil if the
  2225. passed argument is a branch, that is, a node that can have children.
  2226. CHILDREN is a function of one argument that returns the children
  2227. of the passed branch node.
  2228. Non-branch nodes are simply copied."
  2229. (cons tree
  2230. (when (funcall branch tree)
  2231. (-mapcat (lambda (x) (-tree-seq branch children x))
  2232. (funcall children tree)))))
  2233. (defmacro --tree-seq (branch children tree)
  2234. "Anaphoric form of `-tree-seq'."
  2235. `(-tree-seq (lambda (it) ,branch) (lambda (it) ,children) ,tree))
  2236. (defun -clone (list)
  2237. "Create a deep copy of LIST.
  2238. The new list has the same elements and structure but all cons are
  2239. replaced with new ones. This is useful when you need to clone a
  2240. structure such as plist or alist."
  2241. (declare (pure t) (side-effect-free t))
  2242. (-tree-map 'identity list))
  2243. (defun dash-enable-font-lock ()
  2244. "Add syntax highlighting to dash functions, macros and magic values."
  2245. (eval-after-load 'lisp-mode
  2246. '(progn
  2247. (let ((new-keywords '(
  2248. "!cons"
  2249. "!cdr"
  2250. "-each"
  2251. "--each"
  2252. "-each-indexed"
  2253. "--each-indexed"
  2254. "-each-while"
  2255. "--each-while"
  2256. "-doto"
  2257. "-dotimes"
  2258. "--dotimes"
  2259. "-map"
  2260. "--map"
  2261. "-reduce-from"
  2262. "--reduce-from"
  2263. "-reduce"
  2264. "--reduce"
  2265. "-reduce-r-from"
  2266. "--reduce-r-from"
  2267. "-reduce-r"
  2268. "--reduce-r"
  2269. "-reductions-from"
  2270. "-reductions-r-from"
  2271. "-reductions"
  2272. "-reductions-r"
  2273. "-filter"
  2274. "--filter"
  2275. "-select"
  2276. "--select"
  2277. "-remove"
  2278. "--remove"
  2279. "-reject"
  2280. "--reject"
  2281. "-remove-first"
  2282. "--remove-first"
  2283. "-reject-first"
  2284. "--reject-first"
  2285. "-remove-last"
  2286. "--remove-last"
  2287. "-reject-last"
  2288. "--reject-last"
  2289. "-remove-item"
  2290. "-non-nil"
  2291. "-keep"
  2292. "--keep"
  2293. "-map-indexed"
  2294. "--map-indexed"
  2295. "-splice"
  2296. "--splice"
  2297. "-splice-list"
  2298. "--splice-list"
  2299. "-map-when"
  2300. "--map-when"
  2301. "-replace-where"
  2302. "--replace-where"
  2303. "-map-first"
  2304. "--map-first"
  2305. "-map-last"
  2306. "--map-last"
  2307. "-replace"
  2308. "-replace-first"
  2309. "-replace-last"
  2310. "-flatten"
  2311. "-flatten-n"
  2312. "-concat"
  2313. "-mapcat"
  2314. "--mapcat"
  2315. "-copy"
  2316. "-cons*"
  2317. "-snoc"
  2318. "-first"
  2319. "--first"
  2320. "-find"
  2321. "--find"
  2322. "-some"
  2323. "--some"
  2324. "-any"
  2325. "--any"
  2326. "-last"
  2327. "--last"
  2328. "-first-item"
  2329. "-second-item"
  2330. "-third-item"
  2331. "-fourth-item"
  2332. "-fifth-item"
  2333. "-last-item"
  2334. "-butlast"
  2335. "-count"
  2336. "--count"
  2337. "-any?"
  2338. "--any?"
  2339. "-some?"
  2340. "--some?"
  2341. "-any-p"
  2342. "--any-p"
  2343. "-some-p"
  2344. "--some-p"
  2345. "-some->"
  2346. "-some->>"
  2347. "-some-->"
  2348. "-all?"
  2349. "-all-p"
  2350. "--all?"
  2351. "--all-p"
  2352. "-every?"
  2353. "--every?"
  2354. "-all-p"
  2355. "--all-p"
  2356. "-every-p"
  2357. "--every-p"
  2358. "-none?"
  2359. "--none?"
  2360. "-none-p"
  2361. "--none-p"
  2362. "-only-some?"
  2363. "--only-some?"
  2364. "-only-some-p"
  2365. "--only-some-p"
  2366. "-slice"
  2367. "-take"
  2368. "-drop"
  2369. "-drop-last"
  2370. "-take-last"
  2371. "-take-while"
  2372. "--take-while"
  2373. "-drop-while"
  2374. "--drop-while"
  2375. "-split-at"
  2376. "-rotate"
  2377. "-insert-at"
  2378. "-replace-at"
  2379. "-update-at"
  2380. "--update-at"
  2381. "-remove-at"
  2382. "-remove-at-indices"
  2383. "-split-with"
  2384. "--split-with"
  2385. "-split-on"
  2386. "-split-when"
  2387. "--split-when"
  2388. "-separate"
  2389. "--separate"
  2390. "-partition-all-in-steps"
  2391. "-partition-in-steps"
  2392. "-partition-all"
  2393. "-partition"
  2394. "-partition-after-item"
  2395. "-partition-after-pred"
  2396. "-partition-before-item"
  2397. "-partition-before-pred"
  2398. "-partition-by"
  2399. "--partition-by"
  2400. "-partition-by-header"
  2401. "--partition-by-header"
  2402. "-group-by"
  2403. "--group-by"
  2404. "-interpose"
  2405. "-interleave"
  2406. "-unzip"
  2407. "-zip-with"
  2408. "--zip-with"
  2409. "-zip"
  2410. "-zip-fill"
  2411. "-zip-lists"
  2412. "-zip-pair"
  2413. "-cycle"
  2414. "-pad"
  2415. "-annotate"
  2416. "--annotate"
  2417. "-table"
  2418. "-table-flat"
  2419. "-partial"
  2420. "-elem-index"
  2421. "-elem-indices"
  2422. "-find-indices"
  2423. "--find-indices"
  2424. "-find-index"
  2425. "--find-index"
  2426. "-find-last-index"
  2427. "--find-last-index"
  2428. "-select-by-indices"
  2429. "-select-columns"
  2430. "-select-column"
  2431. "-grade-up"
  2432. "-grade-down"
  2433. "->"
  2434. "->>"
  2435. "-->"
  2436. "-as->"
  2437. "-when-let"
  2438. "-when-let*"
  2439. "--when-let"
  2440. "-if-let"
  2441. "-if-let*"
  2442. "--if-let"
  2443. "-let*"
  2444. "-let"
  2445. "-lambda"
  2446. "-distinct"
  2447. "-uniq"
  2448. "-union"
  2449. "-intersection"
  2450. "-difference"
  2451. "-powerset"
  2452. "-permutations"
  2453. "-inits"
  2454. "-tails"
  2455. "-common-prefix"
  2456. "-common-suffix"
  2457. "-contains?"
  2458. "-contains-p"
  2459. "-same-items?"
  2460. "-same-items-p"
  2461. "-is-prefix-p"
  2462. "-is-prefix?"
  2463. "-is-suffix-p"
  2464. "-is-suffix?"
  2465. "-is-infix-p"
  2466. "-is-infix?"
  2467. "-sort"
  2468. "--sort"
  2469. "-list"
  2470. "-repeat"
  2471. "-sum"
  2472. "-running-sum"
  2473. "-product"
  2474. "-running-product"
  2475. "-max"
  2476. "-min"
  2477. "-max-by"
  2478. "--max-by"
  2479. "-min-by"
  2480. "--min-by"
  2481. "-iterate"
  2482. "--iterate"
  2483. "-fix"
  2484. "--fix"
  2485. "-unfold"
  2486. "--unfold"
  2487. "-cons-pair?"
  2488. "-cons-pair-p"
  2489. "-cons-to-list"
  2490. "-value-to-list"
  2491. "-tree-mapreduce-from"
  2492. "--tree-mapreduce-from"
  2493. "-tree-mapreduce"
  2494. "--tree-mapreduce"
  2495. "-tree-map"
  2496. "--tree-map"
  2497. "-tree-reduce-from"
  2498. "--tree-reduce-from"
  2499. "-tree-reduce"
  2500. "--tree-reduce"
  2501. "-tree-seq"
  2502. "--tree-seq"
  2503. "-tree-map-nodes"
  2504. "--tree-map-nodes"
  2505. "-clone"
  2506. "-rpartial"
  2507. "-juxt"
  2508. "-applify"
  2509. "-on"
  2510. "-flip"
  2511. "-const"
  2512. "-cut"
  2513. "-orfn"
  2514. "-andfn"
  2515. "-iteratefn"
  2516. "-fixfn"
  2517. "-prodfn"
  2518. ))
  2519. (special-variables '(
  2520. "it"
  2521. "it-index"
  2522. "acc"
  2523. "other"
  2524. )))
  2525. (font-lock-add-keywords 'emacs-lisp-mode `((,(concat "\\_<" (regexp-opt special-variables 'paren) "\\_>")
  2526. 1 font-lock-variable-name-face)) 'append)
  2527. (font-lock-add-keywords 'emacs-lisp-mode `((,(concat "(\\s-*" (regexp-opt new-keywords 'paren) "\\_>")
  2528. 1 font-lock-keyword-face)) 'append))
  2529. (--each (buffer-list)
  2530. (with-current-buffer it
  2531. (when (and (eq major-mode 'emacs-lisp-mode)
  2532. (boundp 'font-lock-mode)
  2533. font-lock-mode)
  2534. (font-lock-refresh-defaults)))))))
  2535. (provide 'dash)
  2536. ;;; dash.el ends here