Lisp - 對映函式



對映函式是一組可以依次應用於一個或多個元素列表的函式。將這些函式應用於列表的結果將放置在一個新的列表中,並返回該新列表。

例如,mapcar 函式處理一個或多個列表的連續元素。

mapcar 函式的第一個引數應該是函式,其餘引數是要應用函式的列表。

引數函式應用於連續元素,從而生成一個新構造的列表。如果引數列表長度不相等,則在到達最短列表的末尾時對映過程停止。生成的列表將與最短輸入列表具有相同數量的元素。

示例

讓我們從一個簡單的示例開始,並將數字 1 新增到列表 (23 34 45 56 67 78 89) 中的每個元素。

建立一個名為 main.lisp 的新原始碼檔案,並在其中鍵入以下程式碼。

main.lisp

; apply mapping of addition of 1 to each argument
(write (mapcar '1+  '(23 34 45 56 67 78 89)))

輸出

執行程式碼時,它將返回以下結果:

(24 35 46 57 68 79 90)

示例

讓我們編寫一個函式,該函式將對列表中的元素進行立方運算。讓我們使用 lambda 函式來計算數字的立方。

更新名為 main.lisp 的原始碼檔案,並在其中鍵入以下程式碼。

main.lisp

; define a function to apply mapping of qubing each element of the passed list
(defun cubeMylist(lst)
   (mapcar #'(lambda(x) (* x x x)) lst)
)
; print the result of function cubeMylist
(write (cubeMylist '(2 3 4 5 6 7 8 9)))

輸出

執行程式碼時,它將返回以下結果:

(8 27 64 125 216 343 512 729)

示例

更新名為 main.lisp 的原始碼檔案,並在其中鍵入以下程式碼。

main.lisp

; apply addition of each element of first list
; to corresponding element of second list
; result will be restricted to size of smaller list
(write (mapcar '+ '(1 3 5 7 9 11 13) '( 2 4 6 8)))

輸出

執行程式碼時,它將返回以下結果:

(3 7 11 15)
lisp_functions.htm
廣告

© . All rights reserved.