2013-03-04 64 views
2

列表我怎麼會去製作,將採取一些和列表分區列表進入列表,其大小由數 所以給出較小的列表分區功能分區的方案

Partition 3 '(a b c d e f g h) -> '((a b c) (d e f) (g h)) and etc. using take and drop? 

回答

2

我會給你一些提示,所以你可以自己找到答案。填充這一空白:

(define (partition n lst) 
    (cond (<???>      ; if the list is empty 
     <???>)      ; then return the empty list 
     ((< <???> n)    ; if the lists' length is less than n 
     <???>)      ; return a list with lst as its only element 
     (else      ; otherwise 
     (cons      ; cons a list with the result of 
      (<???> lst n)    ; grabbing the first n elements of lst with 
      (<???> n     ; the result of advancing the recursion and 
       (<???> lst n)))))) ; removing the first n elements of lst 

顯然,你就必須在解決方案中使用takedrop的地方,如問題描述請求。像這樣測試你的解決方案:

(partition 3 '(a b c d e f g h)) 
=> '((a b c) (d e f) (g h)) 

(partition 3 '(a b c d e f g h i)) 
=>'((a b c) (d e f) (g h i)) 
+0

非常感謝!我填補了它的空白,我得到 (條件((空?LST) LST ((<(長度LST)N) LST) (否則 (缺點(帶LST N) (分段N (drop lst n)))))) 但是當我這樣做時(分區3'(abcdefgh))我得到 ((abc)(def)gh),所以它在g之前缺少括號,我想知道我是什麼做錯了,所以我可以讓它'((abc)(def)(gh))而不是(.... gh)。我的drop或take函數寫錯了,導致這種情況(必須寫自己的take&drop) – user1869703 2013-03-04 01:03:27

+0

@ user1869703注意,在第二種情況下,您必須返回「列表爲lst作爲其唯一元素」。換句話說,這個:'(list lst)' – 2013-03-04 01:10:48

+1

噢好吧,謝謝你的幫助。 – user1869703 2013-03-04 01:14:06