(方案)如何减去一元数列表?

时间:2013-04-24 16:03:14

标签: list scheme

我正在制作一个功能,用于减少包含一元数的两个列表(l l l = 3或l l l l = 4)

所以,它需要这样做:

~(usub '(l l l l) '(l l))
(l l)

现在,我有一个功能可以添加它们但不会减去它们。我认为这将接近添加一个,但我无法弄明白。帮助

(define (uadd ls1 ls2)
  (if (null? ls1) ls2
    (cons (car ls1) (uadd (cdr ls1) ls2))))

1 个答案:

答案 0 :(得分:0)

减去它的程序与添加的程序非常相似,根本区别在于我们不必在此过程中构建新的列表,而是返回我们减去的列表的子列表来自(此代码中的ls1):

 ; implements unary subtraction between two unary lists
 ; assuming that length(ls1) >= length(ls2)
 ; ls1: list we're subtracting from
 ; ls2: list we're subtracting
 ; returns ls1 - ls2
(define (usub ls1 ls2)
  (if <???>                ; is the list we're subtracting empty?
      <???>                ; then return the list we're subtracting from
      (usub <???> <???>))) ; advance the recursion

显然,诀窍是知道 如何推进递归:注意我们正在缩小两个列表的大小,直到其中一个用完为止,此时我们返回另一个 - 这就是如何我们减去。例如:

(usub '(l l l l l) '(l l))
=> '(l l l)