Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Mapping Functions in LISP

  • Last Updated : 22 Nov, 2021

In this article, we will discuss mapping functions in lisp. Mapping functions are applied on the list data structure for combining one or more lists of elements. By using this we can perform mathematical operations and can join the elements.

The main advantage of this function is that we can combine two or more lists with different sizes.

we can also use these functions in our user-defined functions

Syntax:

mapcar operation list1 list2 ..........list n

where,

  • mapcar is the keyword to map the lists
  • operation is ued to perform two or more lists
  • lists are the input lists to be mapped

Example 1: Lisp program to map the list by adding 1 to all the numbers in the list.

Lisp




;add the number 1 to all the numbers in the list and 
;display
(write (mapcar '1+  '(1 2 3 4 5)))

Output:

(2 3 4 5 6)

Example 2: Perform squaring and cubing of numbers

Lisp




;function to square all the elements by mapping the elements
(
defun squaredata(data)
   (mapcar #'(lambda(i) (* i i )) data)
)
  
; function to cube all the elements by mapping the elements
(
defun cubedata(data)
   (mapcar #'(lambda(i) (* i i i )) data)
)
  
;call the square function
(write (squaredata '(1 2 3 4 5)))
  
;call the cube function
(write (cubedata '(1 2 3 4 5)))

Output:

(1 4 9 16 25)(1 8 27 64 125)

Example 3: Program to map two lists by performing arithmetic operations

Lisp




;map lists by performing addition
(write (mapcar '+ '(1 2 3 4 5) '( 5 7 8 3 2)))
  
(terpri)
  
;map lists by performing subtraction
(write (mapcar '- '(1 2 3 4 5) '( 5 7 8 3 2)))
  
(terpri)
  
;map lists by performing multiplication
(write (mapcar '* '(1 2 3 4 5) '( 5 7 8 3 2)))
  
(terpri)
  
;map lists by performing division
(write (mapcar '/ '(1 2 3 4 5) '( 5 7 8 3 2)))
  
(terpri)

Output:

(6 9 11 7 7)
(-4 -5 -5 1 3)
(5 14 24 12 10)
(1/5 2/7 3/8 4/3 5/2)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!