Richard Dunn
Richard Dunn

Reputation: 6780

Return types in Racket \ Scheme

I'm new to Scheme and I'm wondering how to tidy up the returned values from a recursive function I wrote as an assignment. The function simply prints out a BST in order of lowest to highest value. My question is a bit pedantic, but I'm curious. The output of the function is a list of numbers, but the recursive implementation results in an empty list being returned at the very end. i.e. 8 16 20 '(). Is there a simple way to just return the list of numbers and leave out the empty list? I can imagine a couple of ways of doing it; building a new list or string and returning that at the end, but it would add a fair bit of overhead for such a simple task. Is there any simpler way to achieve this result? Thanks.

Note: The assignment is finished and I should have full marks at this point, so it's not a homework question.

#lang racket

(define (show lst)

  (cond
    [(null? (cadr lst))
     '()]

    ; recur smaller tree
    [(< (car lst) (caaddr lst))
     (show (cadr lst))
     ])

  ; print cur node
  (writeln (car lst))

  (cond
    [(null? (cadr lst))
     '()]

    ; recur larger tree
    [(show (caddr lst))])

)

(show '(16 (8 (2 () ()) (10 () ())) (20 (18 () ()) (30 () ()))))

Upvotes: 0

Views: 561

Answers (1)

uselpa
uselpa

Reputation: 18917

You could replace '() by (void) in your code since the REPL will not print this value. Or just avoid giving return values altogether:

(define (show lst)
  (unless (null? (cadr lst))
    (when (< (car lst) (caaddr lst))
      (show (cadr lst))))
  (writeln (car lst))
  (unless (null? (cadr lst))
    (show (caddr lst))))

Upvotes: 1

Related Questions