문제

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