LISP 根据第一个列表中每个元素的值用另一个列表中的元素替换一个列表中的元素

标签 lisp common-lisp

我有两个列表。 L1 = '(( 8 6 8 7 8 8 ) ( 8 7 7 6 8 7))

L2 = '( (P (Q R)) (Q (P U)) (R( T Q S)) (S (R U Q)) (T( P Q )) (U( R P)) )

对于 L2 中的每个元素,我想将其替换为 L1 列表中的适当元素。

L2 中的每个 P 都应替换为 L1 中每个子列表的第一个元素

L2 中的每个 Q 都应替换为 L1 中每个子列表的第二个元素

L2 中的每个 R 都应替换为 L1 中每个子列表的第 3 个元素

L2 中的每个 S 都应替换为 L1 中每个子列表的第 4 个元素

L2 中的每个 T 都应替换为 L1 中每个子列表的第 5 个元素

L2 中的每个 U 都应替换为 L1 中每个子列表的第 6 个元素

根据第一个子列表,结果 L2 是 '(( 8 ( 6 7)) ( 6 ( 8 8)) (8 (8 6 7)) (7 (8 8 6)) (8 ( 8 6) )) (6( 8 8))

 setq L1  '(( 8 6 8 7 8 8 ) (  8 7  7 6 8 7))
 setq L2  '( (P (Q R)) (Q (P U)) (R( T Q S)) (S (R U Q)) (T( P Q ) (U( R P)) )
(dolist(ele L1)
 (dolist(ele2 L2)
  (progn (substitute (nth 0 L1) 'p ele2)(substitute (nth 1 L1) 'q ele2)
  (substitute (nth 0 L1) 'r ele2)(substitute (nth 0 L1) 's ele2)
  (substitute (nth 0 L1) 't ele2)(substitute (nth 0 L1) 'u ele2))))

谢谢

最佳答案

我不确定你的例子,但这可能会让你开始:

(defun f (mapvals sxp)
  (let ((mapping nil)) 
    (labels
        ((sub (sxp) ; local function - recursive tree traversal
           (cond
            ((null sxp)  nil)
            ((consp sxp) (cons (sub (car sxp)) (sub (cdr sxp))))
            (t                  ; we have an atom, so let's replace it
             (let ((val (assoc sxp mapping))) ; look up the mapping of the atom
               (if val          ; mapping exists?
                   (cdr val)    ; yes, use associated value
                   (let ((newval (pop mapvals)))  ; no, pop next value from mapvals
                     (setf mapping (cons (cons sxp newval) mapping)) ; and remember mapping
                     newval)))))))
      (sub sxp))))

测试:

? (f '(1 2 3 4 5 6)
     '((P (Q R)) (Q (P U)) (R (T Q S)) (S (R U Q)) (T (P Q)) (U (R P))))
((1 (2 3)) (2 (1 4)) (3 (5 2 6)) (6 (3 4 2)) (5 (1 2)) (4 (3 1)))

关于LISP 根据第一个列表中每个元素的值用另一个列表中的元素替换一个列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26476999/

相关文章:

matlab - 循环中的 Common Lisp 暂停命令

lisp - SBCL 多线程写入标准输出

emacs - 如何获取对 Emacs Slime 中最后返回对象的引用

lisp - 在 Common Lisp 中通过对象引用传递

lisp - LISP 有哪些变种?

Clojure 示例 : I cannot comprehend what are the values of "%2" and "%1" in "(str %2 %1)"

emacs - 如何更改/删除 Emacs 菜单项?

lisp - 无法更改列表

lisp - 在 lisp 中,我如何测量和捕获评估表达式所花费的时间?

macros - 在 Common Lisp 中获取宏的堆栈跟踪模拟