Lisp - Sequence Mapping



In Lisp, Sequence is a fundamental data structure and is used to represent list, vectors as a collection of elements or Strings. Mapping a sequence means applying a function over each element of the sequence and results in new sequence. Lisp provides two built-in methods to achive this functionality.

  • mapcar− mapcar function is most popular and widely used function for mapping over list elements. mapcar function applies the given function to each element and results in new list.

  • map− map function is a generic function for mapping over sequence elements and can work on lists as well as vectors. map function applies the given function to each element of one or more sequences and results in new list.

Using mapcar function

Following example, shows usage of mapcar to square each number of a list.

main.lisp

; square each number and print the result
(print(mapcar #'(lambda (x) (* x x)) '(1 2 3 4 5)))

Output

When you execute the code, it returns the following result −

(1 4 9 16 25)

Using map function to add numbers of two lists

Following example, shows usage of map to add each number of a list with corresponding number of second list.

main.lisp

; sum each number correspondingly and print the list
(print(map 'list #'+ '(1 2 3) '(4 5 6)))

Output

When you execute the code, it returns the following result −

(5 7 9) 

Using map function to change case of a String

Following example, shows usage of map to convert a string to upper case string.

main.lisp

; convert the string to uppercase
(write-line(map 'string #'char-upcase "tutorialspoint"))

Output

When you execute the code, it returns the following result −

TUTORIALSPOINT

Key Points

  • Mapping functions are very useful when we need to do the transformation of elements of a sequence.

  • Using lambda function is the preferred way to specify mapping function as it is concise and improves readability of the code.

  • Use mapcar function in case of List, and more generic map for other types of sequence to apply mappings.

Advertisements