user1800967
user1800967

Reputation: 955

DrRacket recursive function

I'm new to the racket programming language so as a quick test, I typed this up on DrRacket:

>(define (test k)
 (when (not (= k 0))
  (begin
   k
    (test (- k 1)))))
>(test 5)

I expected an output of: 54321

but instead got nothing in return...

Tried an alternate approach:

>(define (test k)
  (when (not (= k 0))
   (begin
     (test (- k 1)) k)))
>(test 5)

but this only printed the number 5. I'm not sure what's going on. What am I doing wrong? Any help is greatly appreciated and thank you so much in advance!

Upvotes: 0

Views: 709

Answers (2)

Óscar López
Óscar López

Reputation: 236004

You have to explicitly print the value if you want it to be shown on the console, otherwise the line with the k is doing nothing - remember, Scheme is at its core a functional programming language, and a conditional returns the value of the last expression, all the others are just executed for the effect, but don't return a value. A couple of tips:

(define (test k)
  (unless (zero? k)   ; use unless instead of when-not, zero? instead of (= x 0)
    (display k)       ; display prints in console
    (test (sub1 k)))) ; use sub1 instead of (- x 1)

Upvotes: 4

user1800967
user1800967

Reputation: 955

Just tried a different approach and that seemed to yield results:

> (define (prnt k) k)
> (define (test k)
 (when (not (= k 0))
  (begin
   (print k)
    (test (- k 1)))))
> (test 5)

This printed 54321 which is the behavior I expected. Not too sure why this works but previous attempts didn't but if anyone could shed light on the topic, that would be greatly appreciated!

Upvotes: 0

Related Questions