如何在mapcar中指定替换参数?

Dis*_*les 2 lisp common-lisp

例如,我有一个"字符串"列表:("First""second""third.").
我需要将所有"s"替换为"a" - >(("Firat")......等我发现了非常漂亮的函数,称为替换,但它仅适用于一个序列.
我可以在mapcar中使用替换吗?像这样的东西:

(mapcar 'substitute #\d #\o '(("test") ("wow") ("waow")))
Run Code Online (Sandbox Code Playgroud)

jki*_*ski 5

你可以包围LAMBDA一下这个函数:

(mapcar (lambda (string) (substitute #\d #\o string)) '("test" "wow" "waow"))
;=> ("test" "wdw" "wadw")
Run Code Online (Sandbox Code Playgroud)

或者您可以使用调用的辅助函数CURRY(它不是Common Lisp标准的一部分,但例如在Alexandria中可用).

(ql:quickload :alexandria)
(use-package :alexandria)
(mapcar (curry #'substitute #\d #\o) '("test" "wow" "waow"))
;=> ("test" "wdw" "wadw")
Run Code Online (Sandbox Code Playgroud)

对于子列表中的多个字符串,您可以使用嵌套的mapcar/lambda:

(mapcar (lambda (sentence) 
          (mapcar (lambda (string) 
                    (substitute #\d #\o string))
                  sentence))
        '(("I" "like" "my" "dog.") ("My" "dog" "likes" "me" "too.")))
;=> (("I" "like" "my" "ddg.") ("My" "ddg" "likes" "me" "tdd."))
Run Code Online (Sandbox Code Playgroud)

内在LAMBDA也可以改为CURRY:

(mapcar (lambda (sentence) 
          (mapcar (curry #'substitute #\d #\o) sentence))
        '(("I" "like" "my" "dog.") ("My" "dog" "likes" "me" "too.")))
Run Code Online (Sandbox Code Playgroud)

甚至:

(mapcar (curry #'mapcar (curry #'substitute #\d #\o))
        '(("I" "like" "my" "dog.") ("My" "dog" "likes" "me" "too.")))
Run Code Online (Sandbox Code Playgroud)