因此,我正在浏览我的编程语言模块的一些过去的论文,我遇到了这个问题,我不知道如何去做。
Q:“定义一个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)发布于 2016-10-11 10:07:55
我认为这应该是可行的:
(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)发布于 2016-10-11 18:58:31
在这里,基于累加器的方法是有效的:
(define (repeat n s (result '()))
(if (positive? n)
(repeat (- n 1) s (cons s result))
result))用于或不带初始值result
> (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 (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)发布于 2016-10-12 04:39:30
下面的版本使用for/list两次创建列表列表,然后将列表扁平化并反转:
(define (f l k)
(reverse
(flatten
(for/list ((i k)(n (length k)))
(for/list ((x i))
(list-ref l n))))))还可以使用通用的、高度灵活的“命名让”方法进行循环。不需要反转,因为“cons”会产生一个反向列表:
(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)))))https://stackoverflow.com/questions/39973046
复制相似问题