1

我有一个帮手来复制列表:

(define (list-copy list)
  (if (null? list)
      '()
      (cons (car list) (list-copy (cdr list)))))

然后,

(define (multList lst1 lst2)
  (define lstCopy2 (list-copy lst2))  
  (cond ((null? lst1) ())
        ((eq? (length lst1) (length lst2)) (cons (* (car lst1) (car lst2)) (multList (cdr lst1) (cdr lst2)))) 
        ((> (length lst1) (length lst2))
         (if (null? lst2) lstCopy2
         (cons (* (car lst1) (car lst2)) (multList (cdr lst1) (cdr lst2)))))
        (else '())))

我正在尝试将 lst2 复制到 lstCopy2 中,然后我希望 lstCopy2 在我处理 lst2 时保持不变,以便像最初一样调用 lst2(在 lstCopy2 的帮助下)。在我的第三个条件(当长度 lst1 > 长度 lst2)当 lst2 =()时,我想继续这个过程,直到 lst1 是()。

谢谢你的帮助

4

2 回答 2

2

据我所知,您的副本没有被使用。此外,任何过程都不会改变任何东西,因此对于列表的每个递归/元素(equal? lst2 lstCopy2)总是如此#t

如果lst1短于lst2或者你已经到达列表的末尾,你会得到一个错误,因为()它是一个非法的表达式。也许你的意思是'()

这本可以写得容易得多:

(require srfi/1)

(define (multList lst1 lst2)
  (define (aux lst1 lst2)
    (if (null? lst2)
        '()
        (cons (* (car lst1) 
                 (car lst2)) 
              (aux (cdr lst1) (cdr lst2)))))
  (aux (apply circular-list lst1) lst2))

(multList '(1 -1) '(1 2 3 4 5 6)) ; ==> (1 -2 3 -4 5 -6)

;; with srfi-1-version of map we can use it to make the code shorter
(define (multList lst1 lst2)
  (map * (apply circular-list lst1) lst2))
于 2013-10-26T16:02:37.330 回答
1

你正在以一种非常奇怪的方式解决这个问题。执行此操作的标准方法是定义内部函数。通常你内部函数然后调用它。

每次调用 multList 时,您都在制作 lst2 的副本,这不是我认为您想要的。

但是我看不到您实际引用原始第二个列表的位置,所以我看不出您想要做什么的原因。

(define (multList oL1 oL2)
  (define (helper lst1 lst2)
     (cond ((null? lst1) '())   
           ((null? lst2) (helper lst1 oL2))
           (else
            (cons (* (car lst1) (car lst2)) 
                  (helper (cdr lst1) (cdr lst2))))))
  (helper oL1 oL2))

(multlist '(9 2 4) '(1 2))

;Value 14: (9 4 4)

(multlist '(1 2) '(9 2 4))

;Value 15: (9 4)

明白我说的不是真正的乘法是什么意思吗?(multist ab) 并不总是与 (multlist ba) 相同。

于 2013-10-26T16:16:01.013 回答