方案:从嵌套列表中删除元素

时间:2011-02-12 17:18:37

标签: list scheme

给出一个命题公式,i。即((a and (b implies c) or (d and (e implies f)))), 我需要编写一个Scheme函数来删除连接词andimpliesor。 函数的返回包含公式中的所有变量。例如, (a b c d e f)

我不确定如何开始这个,因为我不确定如何进入嵌套列表并删除cons某些变量和连接词。

1 个答案:

答案 0 :(得分:1)

我会从以下内容开始:

(define somelist
  (list 'a 'and (list 'b 'implies 'c) 
        'or (list 'd 'and (list 'e 'implies 'f))))

(define (remove-vars xs ys)
  (let ((xs-f (flatten xs)))
    (filter-two xs-f ys)))

(define (filter-two xs ys)
  (foldr (lambda(y acc)
           (filter (lambda(x) (not (eq? x y))) acc))
         xs
         ys))

测试:

> (remove-vars somelist (list 'and 'or 'implies))
(a b c d e f)
> (remove-vars somelist (list 'and 'or))
(a b implies c d e implies f)

更新:好的,@ karategeek6报告说,他的Scheme解释器中没有flattenfilter,我不确定你这么做,所以让我们手动实现它们,因为R ^ 6RS中没有filterflatten

(define (my-flatten xs)
  (foldr
   (lambda(x acc)
     (if (list? x)
         (append (my-flatten x) acc)
         (cons x acc)))
   (list)
   xs))

(define (my-filter pred xs)
  (let recur ((xs xs)
              (acc (list)))
    (if (empty? xs)
        (reverse acc)
        (if (pred (car xs))
            (recur (cdr xs) (cons (car xs) acc))
            (recur (cdr xs) acc)))))

适当修改remove-varsfilter-two

(define (remove-vars xs ys)
  (let ((xs-f (my-flatten xs)))
    (filter-two xs-f ys)))

(define (filter-two xs ys)
  (foldr (lambda(y acc)
           (my-filter (lambda(x) (not (eq? x y))) acc))
         xs
         ys))

您应该获得与上述过程的先前版本相同的输出。