2016-10-11 86 views
2

所以我正在瀏覽一些我的Programming Languages模塊的文章,我遇到了這個問題,我不知道該怎麼去做。College Work - Scheme

問:「定義方案函數反向與計數它有兩個 列表,其中第二個是一個非負整數的 長度相同第一列表的列表,並返回元件的列表從 第一個列表按相反順序,每個列表重複 ,由第二個列表的相應元素指定。

例子:

(reverse-with-count '(a b c) '(1 2 3)) => (c c c b b a) 
(reverse-with-count '(d c b a) '(3 0 0 1)) => (a d d d) 

謝謝:)

編輯:

(define (repeat n s) 
    (if (= n 0) 
     '() 
     (append s 
       (repeat (- n 1) s)))) 

使用:

(repeat 10 '(test)) => '(test test test test test test test test test test) 
+1

你可以寫一個函數,它接受一個符號S,N個一產生與N倍的S元素的列表?請至少提供一次嘗試。 – coredump

+0

@coredump見上面.. –

+0

用'cons'而不是'append',你可以用'(repeat 10'test)'調用函數'。另外,要注意輸入中可能的否定'n',你應該使用'<='而不是'='。但這很好。現在,如果你叫'(地圖重複數字符號)',那麼'數字'和'符號'是你的數字和符號列表呢?你會得到一個列表清單。接下來,反轉該列表,並將其所有元素與'(foldr append()...)'連接起來。 – coredump

回答

2

我認爲這應該工作:

(define (multi-element element n) 
    (map (lambda (x) element) (range n))) 

(define (range-list xs ys) 
    (map (lambda (x y) (multi-element x y)) xs ys)) 

(define (reverse-with-count xs ys) 
    (reverse (flatten (range-list xs ys)))) 

輸出:

> (reverse-with-count '(a b c) '(1 2 3)) 
(c c c b b a) 
> (reverse-with-count '(d c b a) '(3 0 0 1)) 
(a d d d) 
> (reverse-with-count '(x baz y z bar g t foo) '(0 1 0 0 1 0 0 1)) 
(foo bar baz) 
0

一種基於累加器的方法是有效的位置:

> (repeat 10 'a) 
'(a a a a a a a a a a) 
> (repeat 10 'a '(initial)) 
'(a a a a a a a a a a initial) 

則第二:

(define (repeat n s (result '())) 
    (if (positive? n) 
     (repeat (- n 1) s (cons s result)) 
     result)) 

具有或不具有初始值result使用程序以相同的方式:

(define (reverse-with-count elts cnts (result '())) 
    (if (or (null? elts) (null? cnts)) 
     result 
     (reverse-with-count (cdr elts) 
          (cdr cnts) 
          (repeat (car cnts) (car elts) result)))) 

測試:用於/列表

> (reverse-with-count '(a b c) '(1 2 3)) 
'(c c c b b a) 
> (reverse-with-count '(a b c) '(1 2 3)) 
'(c c c b b a) 
> (reverse-with-count '(d c b a) '(3 0 0 1)) 
'(a d d d) 
> (reverse-with-count '(x baz y z bar g t foo) '(0 1 0 0 1 0 0 1)) 
'(foo bar baz) 
0

繼版本使用兩次,以創建一個列表的列表,然後將其壓扁和扭轉:

(define (f l k) 
    (reverse 
    (flatten 
    (for/list ((i k)(n (length k))) 
     (for/list ((x i)) 
     (list-ref l n)))))) 

你也可以使用一般高度靈活的'let let'循環方法。倒車不需要爲「缺點」產生反轉列表:

(define (f1 l k) 
    (let loop ((ol '()) 
      (l l) 
      (k k)) 
    (if (null? l) 
     (flatten ol) 
     (loop (cons 
       (for/list ((i (first k))) 
       (first l)) 
       ol) 
       (rest l) 
       (rest k)))))