gpt4 book ai didi

lisp - 如何将列表中的元素映射到 LISP 中其他列表中的值

转载 作者:太空宇宙 更新时间:2023-11-03 19:03:49 25 4
gpt4 key购买 nike

我是 lisp 编程的新手,我正在尝试考虑以下操作。

(extract '(0 1 0) '(a b c)) 给我们'(a b a)

(extract '(1 1 1 ) '(a b c)) 给我们 '(b b b)

我该如何思考这个问题以及如何解决它。

最佳答案

正如 Chris Jester-Young 所描述的,它只是返回第二个列表中第一个列表中索引处的元素。编写这样的函数非常容易:

(defun extract (list-1 list-2)
(mapcar (lambda (n) (nth n list-2)) list-1))

CL-USER>(extract '(0 1 0) '(a b c))
(A B A)
CL-USER>(extract '(1 1 1 ) '(a b c))
(B B B)

如果没有这样的索引,它会在那个地方给你NIL

CL-USER> (extract '(1 100 1 ) '(a b c))
(B NIL B)

但这不适用于嵌套结构(树)。如果你想让它返回 list-2 中 list-1 结构中的元素,你可以使用一个简单的 maptree 辅助函数,然后做同样的事情:

(defun maptree (fn tree)
(cond
((null tree) tree)
((atom tree) (funcall fn tree))
(t (cons
(maptree fn (first tree))
(maptree fn (rest tree))))))


(defun extract* (list-1 list-2)
(maptree (lambda (n)
(nth n list-2)) list-1))

CL-USER> (extract* '(3 (2 1 (0))) '(a b c d))
(D (C B (A)))

关于lisp - 如何将列表中的元素映射到 LISP 中其他列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26770955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com