P15 (**) Replicate the elements of a list a given number of times.

来源:互联网 发布:笑气在淘宝怎么搜 编辑:程序博客网 时间:2024/04/28 21:31

问题描述

sash> (repli '(a b c) 3)sash> (a a a b b b c c c)

解法

(define repli  (lambda (ls n)    (let f ([s ls]            [m n])      (if (null? s)          '()          (if (zero? m)              (f (cdr s) n)              (let ([e (car s)])                (cons e (f s (- m 1)))))))))

与上一个P14类似,也可将每个元素重复形成相应的子列表,然后用append拼接起来。

1 0
原创粉丝点击