Substitutions in Common Lisp

放肆的年华 提交于 2019-12-02 22:40:54

问题


I’m trying to write a function with two arguments of this type:

substitutions (list_one, list_two)

list_one has always this form (letters can change according to the input):

(1 ((1 2 ((1 2 r) (3 2 t) (4 3 c))) (3 4 ((5 6 y) (5 7 i)))))

list_two has always this form (numbers can change according to the input):

(2 3 4 5 6)

I want to substitute in this way:

r-> 2
t -> 3
c -> 4
y -> 5
i -> 6

Can you help me please?


回答1:


A not so efficient solution is to first find a list of all the letters in the fist tree structure (the first list) and then to LOOP over the results calling SUBST repeatedly.

To find the list of non numeric atoms in the first list (the 'letters') you need to traverse the tree structure (le first list) recurring both on the FIRST and on the REST of the list.

Hope it helps.

MA




回答2:


If the lists are proper you can iterate them with the loop macro and pop off the arguments in the accessible free variable:

(defun template-replace (template replacements)
  (labels ((iterate (template)
             (loop :for element :in template
                   :collect
                   (cond ((consp element) (iterate element))
                         ((symbolp element) (pop replacements))
                         (t element)))))
    (iterate template)))


(template-replace '(1 rep (4 rep (9 rep)) rep) '(foot inch mm multiplied))
; ==> (1 foot (4 inch (9 mm)) multiplied)


来源:https://stackoverflow.com/questions/41599987/substitutions-in-common-lisp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!