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)))))