runners3431
runners3431

Reputation: 1455

What's wrong with my recursive procedure?

This procedure takes in a list of booleans, if it sees a false, it should terminate and return false. However the way it's running it's always true.

(define L3 (cons true (cons false empty)))

(check-expect (all-true? L3) false)


(define (all-true? lob)
  (cond [(empty? lob) true]
        [else 
         (if (boolean? (first lob))
         (all-true? (rest lob))
         false)]))

I understand that i could have used an AND clause after the else statement also.

Upvotes: 0

Views: 58

Answers (1)

Óscar López
Óscar López

Reputation: 236112

This should fix the problems:

(define (all-true? lob)
  (cond [(empty? lob) true]
        [(first lob) (all-true? (rest lob))]
        [else false]))

Explanation:

  • If we have several nested conditions, just put them in different branches inside a cond instead of writing an if inside the else part of a cond.
  • We don't want to call boolean?, that's for checking whether a value is boolean, not for determining if it's true.
  • Given that the procedure receives a list of booleans to begin with, testing if the first element is true will be enough to continue the recursion

Alternatively, in Racket we can use andmap for the same effect:

(define (all-true? lob)
  (andmap identity lob))

In other interpreters, we can import every from SRFI-1:

(require srfi/1)
(define (all-true? lob)
  (every (lambda (x) x) lob))

Upvotes: 3

Related Questions