I've been trying hard to do this and it's just frustrating that I can't actually do it. I'm even embarrassed of posting the code I wrote. I'm new to recursion so I need some help over here. What I'm trying to do is to define a function star like this:
> (star 5)
*
**
***
****
*****
It should print * and then ** in the next line and so on up to the number you put. A classic beginner exercise but much more difficult in Racket with recursion. Thank you.
To iterate from 1 to 5 using nothing but recursion:
(let loop ((n 1))
(cond ((> n 5)
(void))
(else
(displayln ...)
(loop (+ 1 n)))))
The above is equivalent to defining a function called loop and then calling it, like this:
(define (loop n)
(cond ((> n 5)
(void))
(else
(displayln ...)
(loop (+ 1 n)))))
(loop 1)
This can appear inside the body of another function:
(define (stars num-stars)
(define (loop ...
To print n stars:
(displayln (make-string n #\*))
Racket isn't raw Scheme, and it has a looping construct of its own, which you could also use:
(for ((n (in-range 1 6)))
(displayln ...))
There's also a library that implements the loop construct from Common Lisp/Maclisp (which also has implementations for Chicken Scheme and EMACS Lisp):
(require (planet jphelps/loop)) ;; Download, install, and
;; use the library.
(loop for n from 1 to 5
do (displayln ...))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With