user3061105
user3061105

Reputation: 19

How to use recursion to automate repetitive tasks in Racket or Scheme?

I'm helping my brother (who'll be starting his studies as a CS major) in functional programming which I'm not very familiar with but understand the principles.

Could you help me in correcting the following Racket script for displaying Hello World 10 times without having to changed or add specific methods such as 'display' ?

Thanks

#lang Racket
    (define (HelloWorld n)
    (cond [(= n 0) " "]
        [(= n 1) "Hello, world !"]
        [(> n 1) (HelloWorld (- n 1))]
        )
    )

Upvotes: 2

Views: 222

Answers (1)

Renzo
Renzo

Reputation: 27424

Your program will display "Hello World!" only once, since in the recursive call you do not print anything. Only the final result of the call is returned, and this consists of the string "Hello World!".

On the other hand, the only way to display n times a string, without printing it, is to produce the result by concatenating the string n times. For instance:

#lang Racket
    (define (HelloWorld n)
    (if (<= n 0)
        ""
       (string-append  "Hello, world ! " (HelloWorld (- n 1)))))

> (HelloWorld 10)
"Hello, world ! Hello, world ! Hello, world ! Hello, world ! Hello, world ! Hello, world ! Hello, world ! Hello, world ! Hello, world ! Hello, world !  "

Note how the recursion works: the final case is n <= 0 (this is better than n = 0 to avoid infinte recursion with a negative input), and in this case the result is the empty string. In case n > 0 the result is obtained concatenating once the string with the result of the function applied to n-1.

Upvotes: 4

Related Questions