2011-11-27 72 views
1

我試圖做方案如下另一個列表中的每個元素:乘以列表中的每個元素與Scheme編程

List<int> list = new List<int>(); 
List<int> list1 = new List<int>(); 
List<int> list2 = new List<int>(); 
list.Add(1); 
list.Add(2); 
list.Add(3); 
list.Add(4); 
list1.Add(2); 
list1.Add(4); 
list1.Add(6); 
list1.Add(8); 

for (int i = 0; i < list.Count; i++) 
{ 
    for (int p = 0; p < list1.Count; p++) 
    { 
     list2.Add(list[i] * list1[p]); 
    } 
} 

所看到上面的代碼,我想乘的每一個元素第一個列表和第二個列表中的每個元素。所以1 * 2,1 * 4,1 * 6,1 * 8,然後去下一個元素,2 * 2,2 * 4 ..等

我有麻煩實施這個到Scheme中。我嘗試使用map函數,但這似乎並不按照我想要的方式工作。有任何想法嗎?

+0

你是如何與地圖以及如何嘗試做它不像你想要的那樣工作?如果你唯一的問題是結果是在嵌套列表中,你可以在之後將它平坦化。 – sepp2k

回答

3

我們首先來定義這兩個輸入列表,我給他們改名,因爲list是方案內置的程序,是不是一個好主意來覆蓋它):

(define l '(1 2 3 4)) 
(define l1 '(2 4 6 8)) 

我假設你希望你的結果列表是「扁平的」 - 例如,它不包含元素列表,僅包含元素列表(如果你確定列表中的列表在l2中,只需將該列表中的列表刪除即可)。爲此,我們需要定義flatten程序:

(define (atom? x) 
    (and (not (pair? x)) (not (null? x)))) 

(define (flatten lst) 
    (cond ((null? lst) empty) 
     ((atom? lst) (list lst)) 
     (else (append (flatten (car lst)) 
         (flatten (cdr lst)))))) 

最後,手頭的問題。一旦您瞭解如何嵌套兩個map程序,這很簡單 - 請參閱SICP本書中的nested mappings部分。

(define l2 
    (flatten 
    (map (lambda (i) 
      (map (lambda (j) 
       (* i j)) 
       l1)) 
     l))) 

在這一點上,l2包含了預期的答案:

(2 4 6 8 4 8 12 16 6 12 18 24 8 16 24 32) 
3

奧斯卡給了一個非常完整的回答了這個問題,但我想補充兩個小筆記:

的計劃方言Racket有一個很好的內置形式,被稱爲for*/list這正是這樣的事情:

(for*/list ([i '(1 2 3 4)] 
      [j '(2 4 6 8)]) 
    (* i j)) 

另外,您也可以不用在嵌套地圖解決方案中使用您自己的或庫中的flatten函數,而是用SRFI-1替換外部mapappend-map。還有很多其他的方法也一樣,當然;-)

1

我不能相信沒有人已經給出了最直接的答案:嵌套用途map

(append-map (lambda (x) 
       (map (lambda (y) (* x y)) 
        (list 2 4 8 6))) 
      (list 1 2 3 4)) 

append-mapmap一個簡單的變體假定映射函數返回一個列表,所以它連接了所有的結果列表。這是最嚴重的計劃系統(它在the SRFI-1 library)的庫函數,但這裏有一個簡單的,不完整的定義(一個完整的定義,將處理多個參數列表):

(define (append-map f xs) 
    (concat (map f xs))) 

;;; 
;;; Turns a list of lists into a list by appending all the top-level sublists. 
;;; This is also a common library function. 
;;; 
(define (concat lists) 
    (if (null? lists) 
     '() 
     (append (car lists) 
       (concat (cdr lists))))) 
相關問題