2016-06-22 47 views
0

成对地我实现,结合两个列表以F两两并返回一个列表的功能(结合FN L1 L2):球拍:如何将两个清单和f

(check-expect (combine string-append "" '("1" "2" "3") '("4" "5" "6")) '("14" "25" "36")) 
(check-expect (combine + 0 '(1 2 3) '(4 5 6)) '(5 7 9)) 


(define (combine f n l1 l2) 
    (if (empty? l1) '() 
     (cons (foldr f n (first (zip l1 l2))) 
     (combine f n (rest l1) (rest l2))))) 

它使用(ZIP L1 L2)功能我以前实现的:

(check-expect (zip '(1 2 3 0) '(4 5 6))'((1 4) (2 5) (3 6))) 

(define (zip l1 l2) 
    (local 
    [(define (take lst n) 
     (if (zero? n) 
      '() 
      (cons (first lst) 
        (take (rest lst)(- n 1))))) 
    (define min-lsts 
     (min (length l1) (length l2)))] 
    (foldr (lambda (e1 e2 acc) (cons (list e1 e2) acc)) '() (take l1 min-lsts) (take l2 min-lsts)))) 

(FN组合L1 L2)按预期工作,但有没有办法将其更改为(结合˚FL1 L2),不指望n,而是仍然使用foldr相似?

在此先感谢!

回答

1

只要你总是有两个参数,你可以用foldr替代递归,只是直接使用两个参数:

(define (combine f l1 l2) 
    (foldr (lambda (a1 a2 acc) 
      (cons (f a1 a2) 
       acc)) 
     '() 
     l1 
     l2)) 

而且拉链实施过于复杂。它可以做得更简单:

(define (zip l1 l2) 
    (map list l1 l2))