Lisp - Using mapcar on List



In LISP, mapcar is powerful tool to work on Lists. mapcar function applies the provided function on each element of the list and returns a new list without modifying the original list.

Syntax

(mapcar function list)

Where

  • function− a function to be applied on each element of the list. We can create a function using #(function-name) or a lambda (anonymous function).

  • list− a list to be iterated.

Let's discover usage of mapcar function with examples−

Performing operations on numbers

In following example code, we're performing few simple mathematical operations on list of numbers and printing them.

main.lisp

; increment each element of list by 1; (2 3 4 5 6)
(print(mapcar #'1+ '(1 2 3 4 5)))  
(terpri)

; get square root of each element; (1 2 3 4 5)
(print(mapcar #'sqrt '(1 4 9 16 25))) 

Output

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

(2 3 4 5 6) 
(1 2 3 4 5) 

Using lambda

In following example code, we're showcasing use of lambda within mapcar function.

main.lisp

; multiply each number by 2
(print(mapcar #'(lambda (x) (* x 2)) '(1 2 3)) )
(terpri)
; multiply even numbers by 10
(print(mapcar #'(lambda (x) (if (evenp x) (* x 10) x)) '(1 2 3 4 5)))

Output

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

(2 4 6) 
(1 20 3 40 5) 

Using mapcar on multiple lists

We can use mapcar on mulple lists provided the function should accept as many parameters as there are lists to be iterated. mapcar will apply function to each element of the list. In case, lists are of different size, mapcar will stop when shortest list end is reached, rest values of other lists will be ignored.

main.lisp

; add corresponding elements and print; (11 22 33)
(print(mapcar #'+ '(1 2 3) '(10 20 30)))
(terpri)
; stops where shortest ends, rest are ignored; (11 22)
(print(mapcar #'+ '(1 2) '(10 20 30))) 

Output

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

(11 22 33) 
(11 22)

Calling named function using mapcar

We can pass a named function to mapcar as well as shown in example where we're converting a string case.

main.lisp

; change string case to UpperCase
(defun string-to-uppercase (str)
  (map 'string #'char-upcase str))  ;

; change case of each string
(print(mapcar #'string-to-uppercase '("Welcome" "To" "Lisp")))

Output

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

("WELCOME" "TO" "LISP") 
Advertisements