map.el 12.5 KB
Newer Older
1 2
;;; map.el --- Map manipulation functions  -*- lexical-binding: t; -*-

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 2015-2016 Free Software Foundation, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

;; Author: Nicolas Petton <nicolas@petton.fr>
;; Keywords: convenience, map, hash-table, alist, array
;; Version: 1.0
;; Package: map

;; Maintainer: emacs-devel@gnu.org

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; map.el provides map-manipulation functions that work on alists,
;; hash-table and arrays.  All functions are prefixed with "map-".
;;
;; Functions taking a predicate or iterating over a map using a
;; function take the function as their first argument.  All other
;; functions take the map as their first argument.

;; TODO:
;; - Add support for char-tables
;; - Maybe add support for gv?
;; - See if we can integrate text-properties
;; - A macro similar to let-alist but working on any type of map could
;;   be really useful

;;; Code:

(require 'seq)

47
(pcase-defmacro map (&rest args)
48
  "Build a `pcase' pattern matching map elements.
49

50
ARGS is a list of elements to be matched in the map.
51

52 53 54 55
Each element of ARGS can be of the form (KEY PAT), in which case KEY is
evaluated and searched for in the map.  The match fails if for any KEY
found in the map, the corresponding PAT doesn't match the value
associated to the KEY.
56

57
Each element can also be a SYMBOL, which is an abbreviation of a (KEY
58
PAT) tuple of the form (\\='SYMBOL SYMBOL).
59

60 61
Keys in ARGS not found in the map are ignored, and the match doesn't
fail."
62
  `(and (pred mapp)
63 64
        ,@(map--make-pcase-bindings args)))

65 66
(defmacro map-let (keys map &rest body)
  "Bind the variables in KEYS to the elements of MAP then evaluate BODY.
67

68 69 70 71
KEYS can be a list of symbols, in which case each element will be
bound to the looked up value in MAP.

KEYS can also be a list of (KEY VARNAME) pairs, in which case
72
KEY is an unquoted form.
73 74

MAP can be a list, hash-table or array."
75
  (declare (indent 2) (debug t))
76
  `(pcase-let ((,(map--make-pcase-patterns keys) ,map))
77 78
     ,@body))

79 80 81
(eval-when-compile
  (defmacro map--dispatch (map-var &rest args)
    "Evaluate one of the forms specified by ARGS based on the type of MAP.
82 83

The following keyword types are meaningful: `:list',
84
`:hash-table' and `:array'.
85 86 87

An error is thrown if MAP is neither a list, hash-table nor array.

88 89 90 91 92 93
Return RESULT if non-nil or the result of evaluation of the form."
    (declare (debug t) (indent 1))
    `(cond ((listp ,map-var) ,(plist-get args :list))
           ((hash-table-p ,map-var) ,(plist-get args :hash-table))
           ((arrayp ,map-var) ,(plist-get args :array))
           (t (error "Unsupported map: %s" ,map-var)))))
94

95
(defun map-elt (map key &optional default)
96
  "Lookup KEY in MAP and return its associated value.
97 98
If KEY is not found, return DEFAULT which defaults to nil.

NicolasPetton's avatar
NicolasPetton committed
99
If MAP is a list, `eql' is used to lookup KEY.
100 101

MAP can be a list, hash-table or array."
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
  (declare
   (gv-expander
    (lambda (do)
      (gv-letplace (mgetter msetter) `(gv-delay-error ,map)
        (macroexp-let2* nil
            ;; Eval them once and for all in the right order.
            ((key key) (default default))
          `(if (listp ,mgetter)
               ;; Special case the alist case, since it can't be handled by the
               ;; map--put function.
               ,(gv-get `(alist-get ,key (gv-synthetic-place
                                          ,mgetter ,msetter)
                                    ,default)
                        do)
             ,(funcall do `(map-elt ,mgetter ,key ,default)
                       (lambda (v) `(map--put ,mgetter ,key ,v)))))))))
118
  (map--dispatch map
NicolasPetton's avatar
NicolasPetton committed
119
    :list (alist-get key map default)
120
    :hash-table (gethash key map default)
121 122 123
    :array (if (and (>= key 0) (< key (seq-length map)))
               (seq-elt map key)
             default)))
124

125
(defmacro map-put (map key value)
126
  "Associate KEY with VALUE in MAP and return MAP.
127
If KEY is already present in MAP, replace the associated value
128 129 130
with VALUE.

MAP can be a list, hash-table or array."
131
  (macroexp-let2 nil map map
132
    `(progn
133 134
       (setf (map-elt ,map ,key) ,value)
       ,map)))
135 136

(defmacro map-delete (map key)
137 138 139
  "Delete KEY from MAP and return MAP.
No error is signaled if KEY is not a key of MAP.  If MAP is an
array, store nil at the index KEY.
140 141

MAP can be a list, hash-table or array."
142
  (declare (debug t))
143 144 145 146 147 148 149 150 151 152
  (gv-letplace (mgetter msetter) `(gv-delay-error ,map)
    (macroexp-let2 nil key key
      `(if (not (listp ,mgetter))
           (map--delete ,mgetter ,key)
         ;; The alist case is special, since it can't be handled by the
         ;; map--delete function.
         (setf (alist-get ,key (gv-synthetic-place ,mgetter ,msetter)
                          nil t)
               nil)
         ,mgetter))))
153 154

(defun map-nested-elt (map keys &optional default)
155
  "Traverse MAP using KEYS and return the looked up value or DEFAULT if nil.
156

157 158
Map can be a nested map composed of alists, hash-tables and arrays."
  (or (seq-reduce (lambda (acc key)
159
                    (when (mapp acc)
160 161 162 163 164 165
                      (map-elt acc key)))
                  keys
                  map)
      default))

(defun map-keys (map)
166 167 168
  "Return the list of keys in MAP.

MAP can be a list, hash-table or array."
169
  (map-apply (lambda (key _) key) map))
170 171

(defun map-values (map)
172 173 174
  "Return the list of values in MAP.

MAP can be a list, hash-table or array."
175
  (map-apply (lambda (_ value) value) map))
176 177

(defun map-pairs (map)
178 179 180
  "Return the elements of MAP as key/value association lists.

MAP can be a list, hash-table or array."
181
  (map-apply #'cons map))
182 183

(defun map-length (map)
184 185 186
  "Return the length of MAP.

MAP can be a list, hash-table or array."
187 188 189
  (length (map-keys map)))

(defun map-copy (map)
190 191 192
  "Return a copy of MAP.

MAP can be a list, hash-table or array."
193 194 195 196 197 198
  (map--dispatch map
    :list (seq-copy map)
    :hash-table (copy-hash-table map)
    :array (seq-copy map)))

(defun map-apply (function map)
199
  "Apply FUNCTION to each element of MAP and return the result as a list.
200 201 202
FUNCTION is called with two arguments, the key and the value.

MAP can be a list, hash-table or array."
203 204 205 206 207 208 209 210
  (funcall (map--dispatch map
             :list #'map--apply-alist
             :hash-table #'map--apply-hash-table
             :array #'map--apply-array)
           function
           map))

(defun map-keys-apply (function map)
211 212 213
  "Return the result of applying FUNCTION to each key of MAP.

MAP can be a list, hash-table or array."
214
  (map-apply (lambda (key _)
215 216 217 218
               (funcall function key))
             map))

(defun map-values-apply (function map)
219 220 221
  "Return the result of applying FUNCTION to each value of MAP.

MAP can be a list, hash-table or array."
222
  (map-apply (lambda (_ val)
223 224 225 226
               (funcall function val))
             map))

(defun map-filter (pred map)
227
  "Return an alist of key/val pairs for which (PRED key val) is non-nil in MAP.
228 229

MAP can be a list, hash-table or array."
230 231 232 233 234 235 236
  (delq nil (map-apply (lambda (key val)
                         (if (funcall pred key val)
                             (cons key val)
                           nil))
                       map)))

(defun map-remove (pred map)
237 238 239
  "Return an alist of the key/val pairs for which (PRED key val) is nil in MAP.

MAP can be a list, hash-table or array."
240 241 242
  (map-filter (lambda (key val) (not (funcall pred key val)))
              map))

243
(defun mapp (map)
244 245 246 247 248 249
  "Return non-nil if MAP is a map (list, hash-table or array)."
  (or (listp map)
      (hash-table-p map)
      (arrayp map)))

(defun map-empty-p (map)
250
  "Return non-nil if MAP is empty.
251 252

MAP can be a list, hash-table or array."
253 254 255 256
  (map--dispatch map
    :list (null map)
    :array (seq-empty-p map)
    :hash-table (zerop (hash-table-count map))))
257

258
(defun map-contains-key (map key &optional testfn)
259
  "Return non-nil if MAP contain KEY, nil otherwise.
260 261 262
Equality is defined by TESTFN if non-nil or by `equal' if nil.

MAP can be a list, hash-table or array."
263
  (seq-contains (map-keys map) key testfn))
264

265 266
(defun map-some (pred map)
  "Return a non-nil if (PRED key val) is non-nil for any key/value pair in MAP.
267 268

MAP can be a list, hash-table or array."
269 270
  (catch 'map--break
    (map-apply (lambda (key value)
271 272 273
                 (let ((result (funcall pred key value)))
                   (when result
                     (throw 'map--break result))))
274 275 276 277
               map)
    nil))

(defun map-every-p (pred map)
278 279 280
  "Return non-nil if (PRED key val) is non-nil for all elements of the map MAP.

MAP can be a list, hash-table or array."
281 282
  (catch 'map--break
    (map-apply (lambda (key value)
283 284 285
              (or (funcall pred key value)
                  (throw 'map--break nil)))
            map)
286 287 288
    t))

(defun map-merge (type &rest maps)
289
  "Merge into a map of type TYPE all the key/value pairs in MAPS.
290 291

MAP can be a list, hash-table or array."
292 293 294
  (let (result)
    (while maps
      (map-apply (lambda (key value)
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
                (setf (map-elt result key) value))
              (pop maps)))
    (map-into result type)))

(defun map-merge-with (type function &rest maps)
  "Merge into a map of type TYPE all the key/value pairs in MAPS.
When two maps contain the same key, call FUNCTION on the two
values and use the value returned by it.
MAP can be a list, hash-table or array."
  (let (result)
    (while maps
      (map-apply (lambda (key value)
                (setf (map-elt result key)
                      (if (map-contains-key result key)
                          (funcall function (map-elt result key) value)
                        value)))
              (pop maps)))
312 313 314 315
    (map-into result type)))

(defun map-into (map type)
  "Convert the map MAP into a map of type TYPE.
316 317 318

TYPE can be one of the following symbols: list or hash-table.
MAP can be a list, hash-table or array."
319 320
  (pcase type
    (`list (map-pairs map))
321
    (`hash-table (map--into-hash-table map))
322
    (_ (error "Not a map type name: %S" type))))
323

324 325 326 327 328 329 330 331
(defun map--put (map key v)
  (map--dispatch map
    :list (let ((p (assoc key map)))
            (if p (setcdr p v)
              (error "No place to change the mapping for %S" key)))
    :hash-table (puthash key v map)
    :array (aset map key v)))

332 333 334 335 336 337 338 339
(defun map--apply-alist (function map)
  "Private function used to apply FUNCTION over MAP, MAP being an alist."
  (seq-map (lambda (pair)
             (funcall function
                      (car pair)
                      (cdr pair)))
           map))

340 341 342 343 344 345 346 347 348
(defun map--delete (map key)
  (map--dispatch map
    :list (error "No place to remove the mapping for %S" key)
    :hash-table (remhash key map)
    :array (and (>= key 0)
                (<= key (seq-length map))
                (aset map key nil)))
  map)

349 350 351 352 353 354 355 356 357 358
(defun map--apply-hash-table (function map)
  "Private function used to apply FUNCTION over MAP, MAP being a hash-table."
  (let (result)
    (maphash (lambda (key value)
               (push (funcall function key value) result))
             map)
    (nreverse result)))

(defun map--apply-array (function map)
  "Private function used to apply FUNCTION over MAP, MAP being an array."
359 360 361 362 363 364
  (let ((index 0))
    (seq-map (lambda (elt)
               (prog1
                   (funcall function index elt)
                 (setq index (1+ index))))
             map)))
365 366 367 368 369 370

(defun map--into-hash-table (map)
  "Convert MAP into a hash-table."
  (let ((ht (make-hash-table :size (map-length map)
                             :test 'equal)))
    (map-apply (lambda (key value)
371
                 (setf (map-elt ht key) value))
372 373 374
               map)
    ht))

375 376 377 378
(defun map--make-pcase-bindings (args)
  "Return a list of pcase bindings from ARGS to the elements of a map."
  (seq-map (lambda (elt)
             (if (consp elt)
379
                 `(app (pcase--flip map-elt ,(car elt)) ,(cadr elt))
380 381 382 383 384 385 386 387 388 389 390 391
               `(app (pcase--flip map-elt ',elt) ,elt)))
           args))

(defun map--make-pcase-patterns (args)
  "Return a list of `(map ...)' pcase patterns built from ARGS."
  (cons 'map
        (seq-map (lambda (elt)
                   (if (and (consp elt) (eq 'map (car elt)))
                       (map--make-pcase-patterns elt)
                     elt))
                 args)))

392 393
(provide 'map)
;;; map.el ends here