typestar

mapcar & reduce in Lisp

Adds tax to a list of cart prices with mapcar, then totals them with reduce.

;; MAPCAR applies a function to every element and collects the answers.
(defvar *cart* '(2.50 3.75 1.20 4.05))

(defun with-tax (price)
  "Return PRICE plus eight percent sales tax."
  (* price 1.08))

;; The function can be a named one or a lambda written in place.
(defvar *taxed* (mapcar #'with-tax *cart*))
(defvar *cents* (mapcar (lambda (price) (round (* 100 price))) *cart*))

;; REDUCE folds a list into a single value; :INITIAL-VALUE seeds the
;; fold, so an empty cart still adds up to zero.
(defvar *total* (reduce #'+ *taxed* :initial-value 0))

(format t "cents ~a~%" *cents*)
(format t "total ~,2f~%" *total*)

How it works

  1. (mapcar #'with-tax *cart*) passes the named function defined just above it.
  2. (mapcar (lambda (price) (round (* 100 price))) *cart*) uses an inline lambda instead.
  3. (reduce #'+ *taxed* :initial-value 0) folds the list to one number and covers the empty case.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
619
Tokens
84
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 72 seconds.

Type this snippet

Step 1 of 3 in Higher-order, step 13 of 27 in Language basics.

← Previous Next →