Reputation: 31
I have a condition statement such as:
(cond
[ (and (null? E1) (not (null? E2))) #f]
[ (and (not (null? E1)) (null? E2)) #f]
[ (or (= (length E1) 1) (= (length E2) 1))
(cond
[ (equal? E1 E2) #t]
[ (equal? (reverse E1) E2) #t]
[ else #f break]
)]
[ .... conditions continue
Is there a way of exiting out of the cond statement, after either the #f or #t is reached, and not continuing to the bottom, checking all the rest of the conditions? Just like in python, there is 'break' to get out of loops.
Upvotes: 0
Views: 985
Reputation: 48765
In a cond
(cond
(predicate1 consequent1)
(predicate2 consequent2)
(else alternative))
It is the same as:
(if predicate1
consequent1
(if predicate2
consequent2
alternative))
Thus if predicate1 matches the expression consequent1 will be the evaluateion of the whole cond
form.
If you nest cond
the evaluation of the whole cond
will be the evaluation of the inner when the predicate for the nested cond matches.
One other difference between if
is that cond
can have more than one consequent/alternative expression since it has explicit begin.. Thus you code where you have `
(cond ...
[else #f break])
Here if the other predicates don't match it will always match else
. Then if will first evaluate #f (which is redundant since it doesn't do any side effects) before it evaluates break
and it's value will be the result.
Upvotes: 0
Reputation: 17223
Hmm... If I understand you correctly, then the behavior you want is the behavior that's built in. Here's an example:
#lang racket
(define (my-fun E1 E2)
(cond
[(and (null? E1) (not (null? E2))) #f]
[(and (not (null? E1)) (null? E2)) #f]
[(or (= (length E1) 1) (= (length E2) 1))
(cond
[(equal? E1 E2) #t]
[(equal? (reverse E1) E2) #t]
[else #f])] ;; <-- the break was here.
[(dont-run-this-check) #t]
[(dont-run-this-check-either) #f]
[(really-really-dont-run-this-check) #t]))
(my-fun '(a b c) '(d))
(define (dont-run-this-check) (error))
(define (dont-run-this-check-either) (error))
(define (really-really-dont-run-this-check) (error))
This evaluates to #f
In this example, the code "breaks" on the line labeled "the break was here", and never evaluates any of the following tests (if it did, you'd see an error). That's because once the outer 'cond' has chosen a clause, none of the rest of them will be evaluated.
Is that what you're looking for?
Upvotes: 2