LISP - Mapping Functions



Mapping functions are a group of functions that could be applied successively to one or more lists of elements. The results of applying these functions to a list are placed in a new list and that new list is returned.

For example, the mapcar function processes successive elements of one or more lists.

The first argument of the mapcar function should be a function and the remaining arguments are the list(s) to which the function is applied.

The argument function is applied to the successive elements that results into a newly constructed list. If the argument lists are not equal in length, then the process of mapping stops upon reaching the end of the shortest list. The resulting list will have the same number of elements as the shortest input list.

Example 1

Let us start with a simple example and add the number 1 to each of the elements of the list ( 23 34 45 56 67 78 89).

Create a new source code file named main.lisp and type the following code in it.

(write (mapcar '1+  '(23 34 45 56 67 78 89)))

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

(24 35 46 57 68 79 90)

Example 2

Let us write a function that would cube the elements of a list. Let us use a lambda function for calculating the cube of numbers.

Create a new source code file named main.lisp and type the following code in it.

(defun cubeMylist(lst)
   (mapcar #'(lambda(x) (* x x x)) lst)
)
(write (cubeMylist '(2 3 4 5 6 7 8 9)))

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

(8 27 64 125 216 343 512 729)

Example 3

Create a new source code file named main.lisp and type the following code in it.

(write (mapcar '+ '(1 3 5 7 9 11 13) '( 2 4 6 8)))

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

(3 7 11 15)
lisp_functions.htm
Advertisements