'Duplicate things a specific number of times in racket

I'm trying to write a program that takes in a phrase and a number (n) and returns a list that contains the phrase repeated n times. What I have so far looks like this, but it clearly only repeats the phrase twice:

(define (duplicate num phrase)
  (list phrase phrase))

Example of desired input/output:

(duplicate 3 'Hello) produces '(Hello Hello Hello).

Is there a way to do this recursively?



Solution 1:[1]

The function you want is exactly make-list:

> (make-list 3 'Hello)
'(Hello Hello Hello)

But since you asked for a recursive function, you can write one out in the standard way.

(define (duplicate num phrase)
  (cond
    [(zero? num) empty]
    [else (cons phrase (duplicate (sub1 num) phrase))]))

You also tagged this with for-loop, so here's a version that uses for/list.

(define (duplicate num phrase)
  (for/list ([num num])
    phrase))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gibstick