Klimi's new dotfiles with stow.
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.

3028 line
100 KiB

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