首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >大学工作-计划

大学工作-计划
EN

Stack Overflow用户
提问于 2016-10-11 08:16:35
回答 3查看 290关注 0票数 2

因此,我正在浏览我的编程语言模块的一些过去的论文,我遇到了这个问题,我不知道如何去做。

Q:“定义一个Scheme函数反向计数,它接受两个列表,第二个列表是一个与第一个列表长度相同的非负整数列表,并从第一个列表中返回一个元素列表,顺序相反,每个元素按第二个列表的相应元素重复多次。”

示例:

代码语言:javascript
复制
(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)

谢谢:)

编辑:

代码语言:javascript
复制
(define (repeat n s)
  (if (= n 0)
      '()
      (append s
              (repeat (- n 1) s))))

使用:

代码语言:javascript
复制
 (repeat 10 '(test)) => '(test test test test test test test test test test)
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-10-11 10:07:55

我认为这应该是可行的:

代码语言:javascript
复制
(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))))

输出:

代码语言:javascript
复制
> (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)
票数 2
EN

Stack Overflow用户

发布于 2016-10-11 18:58:31

在这里,基于累加器的方法是有效的:

代码语言:javascript
复制
(define (repeat n s (result '()))
  (if (positive? n)
      (repeat (- n 1) s (cons s result))
      result))

用于或不带初始值result

代码语言:javascript
复制
> (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)

然后以同样的方式进行第二次程序:

代码语言:javascript
复制
(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))))

测试:

代码语言:javascript
复制
> (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
EN

Stack Overflow用户

发布于 2016-10-12 04:39:30

下面的版本使用for/list两次创建列表列表,然后将列表扁平化并反转:

代码语言:javascript
复制
(define (f l k)
  (reverse
   (flatten
    (for/list ((i k)(n (length k)))
      (for/list ((x i))
        (list-ref l n))))))

还可以使用通用的、高度灵活的“命名让”方法进行循环。不需要反转,因为“cons”会产生一个反向列表:

代码语言:javascript
复制
(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)))))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39973046

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档