📜  LISP 中的映射函数

📅  最后修改于: 2022-05-13 01:54:58.897000             🧑  作者: Mango

LISP 中的映射函数

在本文中,我们将讨论 lisp 中的映射函数。映射函数应用于列表数据结构,用于组合一个或多个元素列表。通过使用它,我们可以执行数学运算并可以连接元素。

这个函数的主要优点是我们可以组合两个或多个不同大小的列表。

我们也可以在我们的用户定义函数中使用这些函数

语法

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

在哪里,

  • mapcar是映射列表的关键字
  • 操作用于执行两个或多个列表
  • 列表是要映射的输入列表

示例 1: Lisp 程序通过将列表中的所有数字加 1 来映射列表。

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


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)))


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)


输出:

(2 3 4 5 6)

示例 2:执行数字的平方和立方

语言

;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)))

输出:

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

示例 3:通过执行算术运算来映射两个列表的程序

语言

;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)

输出:

(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)