我何时会使用mapc而不是mapcar?

Gol*_*den 2 lisp common-lisp map

到目前为止,我一直在使用mapcar将函数应用于列表的所有元素,例如:

(mapcar (lambda (x) (* x x))
        '(1 2 3 4 5))
;; => '(1 4 9 16 25)
Run Code Online (Sandbox Code Playgroud)

现在我了解到还有一个mapc函数完全相同,但不会返回一个新的列表,而是原来的列表:

(mapc (lambda (x) (* x x))
      '(1 2 3 4 5))
;; => '(1 2 3 4 5)
Run Code Online (Sandbox Code Playgroud)

这个功能的意图是什么?当我会用mapc,而不是mapcar如果我不能够访问的结果呢?

Rai*_*wig 12

Common Lisp Hyperspec说:

mapc就像mapcar不同的是应用功能的结果不累加.返回list参数.

因此,在为可能的副作用进行映射时使用它.mapcar可以使用,但mapc减少不必要的消耗.它的返回值也是原始列表,可以用作另一个函数的输入.

例:

(mapc #'delete-file (mapc #'compile-file '("foo.lisp" "bar.lisp")))
Run Code Online (Sandbox Code Playgroud)

上面将首先编译源文件,然后删除源文件.因此编译的文件将保留.

(mapc #'delete-file (mapcar #'compile-file '("foo.lisp" "bar.lisp")))
Run Code Online (Sandbox Code Playgroud)

上面将首先编译源文件,然后删除已编译的文件.