例如,我有一个“字符串”列表:("First""second""third.")。
我需要将所有“s”替换为“a”->((“Firat”)...等
我发现了一个非常漂亮的函数,叫做 substitute,但它只对一个序列有效。
我可以在 mapcar 中使用替代品吗?像这样:
(mapcar 'substitute #\d #\o '(("test") ("wow") ("waow")))
最佳答案
您可以在函数周围包装一个 LAMBDA
:
(mapcar (lambda (string) (substitute #\d #\o string)) '("test" "wow" "waow"))
;=> ("test" "wdw" "wadw")
或者您可以使用一个名为 CURRY
的辅助函数(它不是 Common Lisp 标准的一部分,但在例如 Alexandria 中可用)。
(ql:quickload :alexandria)
(use-package :alexandria)
(mapcar (curry #'substitute #\d #\o) '("test" "wow" "waow"))
;=> ("test" "wdw" "wadw")
对于子列表中的多个字符串,可以使用嵌套的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."))
内部 LAMBDA
也可以更改为 CURRY
:
(mapcar (lambda (sentence)
(mapcar (curry #'substitute #\d #\o) sentence))
'(("I" "like" "my" "dog.") ("My" "dog" "likes" "me" "too.")))
甚至:
(mapcar (curry #'mapcar (curry #'substitute #\d #\o))
'(("I" "like" "my" "dog.") ("My" "dog" "likes" "me" "too.")))
关于lisp - 如何在 mapcar 中指定替代参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814464/