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

3377 lines
115 KiB

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