Function: take-while

take-while is a byte-compiled function defined in subr.el.gz.

Signature

(take-while PRED LIST)

Documentation

Return the longest prefix of LIST whose elements satisfy PRED.

Other relevant functions are documented in the list group.

View in manual

Probably introduced at or before Emacs version 31.1.

Shortdoc

;; list
(take-while #'numberp '(1 2 three 4 five))
    => (1 2)

Source Code

;; Defined in /usr/src/emacs/lisp/subr.el.gz
(defun take-while (pred list)
  "Return the longest prefix of LIST whose elements satisfy PRED."
  (declare (compiler-macro
            (lambda (_form)
              (let* ((tail (make-symbol "tail"))
                     (pred (macroexpand-all pred macroexpand-all-environment))
                     (f (and (not (internal--effect-free-fun-arg-p pred))
                             (make-symbol "f")))
                     (r (make-symbol "r")))
                `(let (,@(and f `((,f ,pred)))
                       (,tail ,list)
                       (,r nil))
                   (while (and ,tail (funcall ,(or f pred) (car ,tail)))
                     (push (car ,tail) ,r)
                     (setq ,tail (cdr ,tail)))
                   (nreverse ,r))))))
  (let ((r nil))
    (while (and list (funcall pred (car list)))
      (push (car list) r)
      (setq list (cdr list)))
    (nreverse r)))