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

时间:2014-11-06 02:53:30

标签: lisp

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

(提取'(0 1 0)'(a b c))给我们'(a b a)

(提取'(1 1 1)'(a b c))给我们'(b b b)

我怎么能想到这个以及如何解决它。

2 个答案:

答案 0 :(得分:1)

正如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-2形状的元素,你可以使用一个简单的maptree helper函数,然后做同样的事情:

(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)))

答案 1 :(得分:0)

(extract a b)会返回a的副本,其中每个元素都会被该位置的b元素替换。

相关问题