Question

I am making a simple code that uses recursion for printing the elements of a list:

(define (printList list)
  (if (empty? list)
      '()
      (begin
        (display (car list))
        (printList (cdr list)))))

It actually works, but I want to know if there is a way that does not print the empty list. When I run my program with (printList '(1 2 3 4)), I got:

1 2 3 4 ()

Any way to solve this?

Thanks

Was it helpful?

Solution

The output you have consists of

  1. the displays : 1234 (color: pink)
  2. the result of the function : '() (color: blue)

Dr Racket will not print the result of the function if it is void, so you could return void in your base case:

(define (printList list)
  (if (empty? list)
      (void)
      (begin
        (display (car list))
        (printList (cdr list)))))

but it would be more elegant to say

(define (printList list)
  (unless (empty? list)
    (display (car list))
    (printList (cdr list))))

which will return void implicitly if the list is empty and doesn't need an explicit begin.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top