【问题标题】:need help for substitute function in scheme方案中的替代功能需要帮助
【发布时间】:2011-10-25 04:12:18
【问题描述】:

我需要编写可以将列表对中的变量替换到列表中的函数。例如(subsitute-var '((p #t) (Q #f)) '(P and Q or Q))

我写了一些代码

(define substitute   
  (lambda (A B list)     
    (cond      
     ((null? list) '())      
     ((list? (car list))
      (cons (substitute A B (car list)) (substitute A B (cdr list))))
     ((eq? (car list) A) (cons B ( substitute A B (cdr list))))      
     (else       
      (cons (car list) (substitute A B (cdr list)))))))

(define substitute-var
  (lambda (list var)
   (cond
     ((null? list) '())
     ((null? var) '())
     ((substitute (caar var) (car (cdr (car var))) list))       
      (substitute-var list (cdr var)))))

但问题是它只替换了第一对 (p #t) 并让列表的其余部分保持不变。我尝试递归调用substitute-var,但它也不起作用。所以我需要帮助。请帮帮我谢谢

【问题讨论】:

  • 而且这个替代变量函数的结果应该是 (subsitute-var '((p #t) (Q #f)) '(P and Q or Q)) => ( #t 和 #f 或 #f)
  • 不幸的是调用了替代list的参数。原因是list 是一个内置函数。我建议称它为 xs 或类似名称。

标签: scheme


【解决方案1】:

我想你把varlist 搞混了

【讨论】:

    【解决方案2】:

    试试这个:

    (define (substitute-var var lst)
      (if (or (null? var) (null? lst))
          '()
          (substitute (car var) (cadr var) lst)))
    
    (define (substitute a b lst)
      (cond ((null? lst) '())
            ((eq? (car lst) (car a))
             (cons (cadr a) (substitute a b (cdr lst))))
            ((eq? (car lst) (car b))
             (cons (cadr b) (substitute a b (cdr lst))))
            (else (cons (car lst) (substitute a b (cdr lst))))))
    

    现在,当用您的示例进行测试时:

    (substitute-var '((P #t) (Q #f)) '(P and Q or Q))
    

    程序返回预期的答案:

    (#t and #f or #f)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多