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.
The mapcar Function for Lists
Section titled “The mapcar Function for Lists”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.
Example: Squaring each number in a list
Section titled “Example: Squaring each number in a list”;; 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))Result
Section titled “Result”(1 4 9 16 25)Example: Adding elements from two lists
Section titled “Example: Adding elements from two lists”(mapcar #'+ '(1 2 3) '(10 20 30))Result
Section titled “Result”(11 22 33)The Generic map Function
Section titled “The Generic map Function”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")Result
Section titled “Result”#(#\L #\i #\s #\p)Example: Converting a string to uppercase
Section titled “Example: Converting a string to uppercase”(map 'string #'char-upcase "tutorialspoint")Result
Section titled “Result”"TUTORIALSPOINT"Alternative: The loop Macro
Section titled “Alternative: The loop Macro”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.
Example: Squaring numbers with loop
Section titled “Example: Squaring numbers with loop”(loop for x in '(1 2 3 4 5) collect (* x x))Result
Section titled “Result”(1 4 9 16 25)Best Practices: When to Use Which?
Section titled “Best Practices: When to Use Which?”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.