谁能解释一下这段代码中发生了什么?

时间:2019-11-05 01:26:49

标签: scheme

Scheme中的此代码用于输出一个列表,其中输入列表的元素重复 n 次。我不明白代码中正在发生什么。

(define (echo-lots lst n)
  (define (helper lst1 n1)
    (if (= n1 0)
        '()
        (cons lst1 (helper lst1 (- n1 1)))))
  (if (null? lst)
      '()
      (append (helper (car lst) n) (echo-lots (cdr lst) n)))

1 个答案:

答案 0 :(得分:1)

首先,请注意helper不使用echo-lots的任何参数。
这意味着您可以将定义移到外面并孤立地找出它:

(define (helper lst1 n1)
    (if (= n1 0)
        '()
        (cons lst1 (helper lst1 (- n1 1)))))

> (helper 1 3)
'(1 1 1)
> (helper #f 4)
'(#f #f #f #f)
> (helper '(a b c) 2)
'((a b c) (a b c))

生成一个列表,该列表的元素是第一个参数,重复第二个参数给出的次数。
(如果您愿意,可以正式证明这一点。)

还要注意,第一个参数的名称具有误导性-它不必是列表。
让我们改进命名:

(define (repeat item n)
    (if (= n 0)
        '()
        (cons item (repeat item (- n 1)))))

现在echo-lots更清晰:

(define (echo-lots lst n)
  (if (null? lst)
      '()
      (append (repeat (car lst) n) 
              (echo-lots (cdr lst) n))))

,更容易看到它制作了n-lst的第一个元素的(repeat (car lst) n)个副本的列表,并将其附加到由n组成的列表中其余每个元素的副本-(echo-lots (cdr lst) n)

相关问题