Function: assoc-default

assoc-default is a byte-compiled function defined in subr.el.gz.

Signature

(assoc-default KEY ALIST &optional TEST DEFAULT)

Documentation

Find object KEY in a pseudo-alist ALIST.

ALIST is a list of conses or objects. Each element
 (or the element's car, if it is a cons) is compared with KEY by
 calling TEST, with two arguments: (i) the element or its car,
 and (ii) KEY.
If that is non-nil, the element matches; then assoc-default
 returns the element's cdr, if it is a cons, or DEFAULT if the
 element is not a cons.

If no element matches, the value is nil. If TEST is omitted or nil, equal is used.

Other relevant functions are documented in the list and alist groups.

View in manual

Probably introduced at or before Emacs version 20.3.

Shortdoc

;; alist
(assoc-default "foobar" '(("foo" . baz)) #'string-match)
    => baz
;; list
(assoc-default 2 '((1 . a) (2 . b) #'=))
    => b

Source Code

;; Defined in /usr/src/emacs/lisp/subr.el.gz
;;;; Various list-search functions.

(defun assoc-default (key alist &optional test default)
  "Find object KEY in a pseudo-alist ALIST.
ALIST is a list of conses or objects.  Each element
 (or the element's car, if it is a cons) is compared with KEY by
 calling TEST, with two arguments: (i) the element or its car,
 and (ii) KEY.
If that is non-nil, the element matches; then `assoc-default'
 returns the element's cdr, if it is a cons, or DEFAULT if the
 element is not a cons.

If no element matches, the value is nil.
If TEST is omitted or nil, `equal' is used."
  (let (found (tail alist) value)
    (while (and tail (not found))
      (let ((elt (car tail)))
	(when (funcall (or test #'equal) (if (consp elt) (car elt) elt) key)
	  (setq found t value (if (consp elt) (cdr elt) default))))
      (setq tail (cdr tail)))
    value))