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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top