Skip to content

LISP - Mapping Sequence Element

Lisp - Functional Programming with Sequences

Section titled “Lisp - Functional Programming with Sequences”

A core strength of Lisp is its support for functional programming. A sequence is an ordered collection of elements, and Common Lisp provides a powerful abstraction for them, covering both lists and vectors. Mapping is the process of applying a function to each element of a sequence to create a new one.

mapcar is the classic mapping function for lists. It takes a function and one or more lists as arguments. It applies the function to corresponding elements from the lists and returns a new list of the results.

;; The #' syntax is a shorthand for (function ...)
;; It gets the function object associated with a symbol or lambda expression.
(mapcar #'(lambda (x) (* x x))
'(1 2 3 4 5))
(1 4 9 16 25)
(mapcar #'+ '(1 2 3) '(10 20 30))
(11 22 33)

map is a more general mapping function. Its first argument specifies the type of sequence to return. This allows you to map over lists, vectors, or strings and produce any type of sequence as a result.

Example: Converting a string to a vector of characters

Section titled “Example: Converting a string to a vector of characters”
;; The `identity` function simply returns its argument.
(map 'vector #'identity "Lisp")
#(#\L #\i #\s #\p)
(map 'string #'char-upcase "tutorialspoint")
"TUTORIALSPOINT"

For more complex iterations, the loop macro is an extremely powerful and idiomatic tool in Common Lisp. It provides a mini-language for expressing loops in a declarative style.

(loop for x in '(1 2 3 4 5)
collect (* x x))
(1 4 9 16 25)
  • mapcar: Use for simple, functional transformations on one or more lists where the result is always a list. It’s clean and highly expressive for this purpose.
  • map: Use when you need the result to be a specific sequence type (like a vector or string) or when you don’t need the result at all (use (map nil ...) for side effects).
  • loop: Use for more complex scenarios. For example, when you need to filter and map simultaneously, iterate over different data structures (like hash tables), or require fine-grained control over the iteration.