简体   繁体   English

替换方案列表中的列表

[英]Replace in a list of lists in scheme

So I have a function that replaces an element of a list with the corespondent element in a list o pairs for example if i have this : (i have a list) and ((have not) (list queue)) it will return (i not a queue) 所以我有一个函数用列表o对中的corespondent元素替换列表的元素,例如,如果我有这个:(我有一个列表)和((没有)(列表队列)),它将返回(i不是队列)

   (define replacecoresp
(lambda (ls a-list)
    (map (lambda (x)
           (let ((lookup (assq x a-list)))
             (if lookup
                 (cadr lookup)
                 x)))
         ls)))

unfortunately it doesn't work for a list of lists of lists etc what I want is to do this : if I have a list (i have ( a list) of (list ( list and list ))) and ((list queue) (have not)) the result should be (I not (a queue) of (queue (queue and queue))) I hope you got the idea :) thanks a lot! 不幸的是,它对于列表列表列表等不起作用,我想要的是这样做:如果我有一个列表(我有(列表)的(列表(列表和列表)))和((列表队列) (没有))结果应该是(我不是(队列(队列和队列))的(一个队列)))我希望您有这个主意:)非常感谢!

Try this: 尝试这个:

(define (replacecoresp ls a-list)
  (cond ((null? ls) '())
        ((not (list? ls))
         (cond ((assq ls a-list) => cadr)
               (else  ls)))
        (else (cons (replacecoresp (car ls) a-list)
                    (replacecoresp (cdr ls) a-list)))))

It works as expected: 它按预期工作:

(replacecoresp '(I have (a list) of (list (list and list)))
               '((list queue) (have not)))

> (I not (a queue) of (queue (queue and queue)))

Explanation: When traversing a list of lists (say, ls ) you need to consider three cases: 说明:遍历列表列表(例如ls )时,需要考虑以下三种情况:

  1. ls is empty, return the empty list ls为空,返回空列表
  2. ls is an atom not a list, process the element ls是原子而不是列表,处理元素
  3. ls is a list, invoke the recursion on both the car and the cdr of the list and combine the results ls是一个列表,同时在car和列表的cdr上调用递归并合并结果

In the particular case of your question, cons is used in the third step for combining the solution; 在您遇到问题的特定情况下,第三步将使用cons来组合解决方案; and the second case is the part where we check to see if the current symbol is in the association list, replacing it if it was found or leaving the symbol untouched if not. 第二种情况是我们检查当前符号是否在关联列表中的部分,如果找到则将其替换,否则将其保留。 I used a shortcut for writing less code in this step, but you can replace the inner cond with this snippet of code if it's clearer: 我在此步骤中使用了一种用于编写更少代码的快捷方式,但是如果更清晰,您可以使用以下代码片段替换内部cond

(let ((lookup (assq ls a-list)))
  (if lookup
      (cadr lookup)
      ls))

Another way to express the solution is to use a map on the list like this: 表达解决方案的另一种方法是使用列表上的map ,如下所示:

(define(replacecoresp ls a-list)
  (if (not (list? ls))
      (cond ((assq ls a-list) => cadr)
            (else  ls))
      (map (lambda (l) (replacecoresp l a-list)) ls)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM