Frage

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

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top