Here's you code, indented so that the corresponding items are visually aligned:
(define (partition lst item)
(define (partition-iter lst less same greater)
(cond
((null? lst)
(list less same greater ))
((< (car lst) item)
(partition-iter (cdr lst)
(cons (car lst) less)
same
greater))
((= (car lst) item)
less
(cons (car lst) same)
(else
(partition-iter (cdr lst)
(cons (car lst) greater))))))
(partition-iter lst '() '() '()))
I think you can see there's something wrong with it right away, now. It's asymmetrical, all out of wack, even if the parens are balanced. An else
clause inside another cond
clause? What is that??
The moral is, don't be afraid to use white space to see better. Lots and lots of white space.
Without it, Scheme tends to look like an impenetrable wall of words, parens or no parens. And the recommended indentation style. Does. Not. Help.
The fix is obvious, minimal, and simple: just complete the code in the same style you (??) started writing it. Handle the other two cases, building the three interim lists while iterating along the input list by taking repeated cdr
s in each of the three cases:
(define (partition lst item)
(define (partition-iter lst less same greater)
(cond
((null? lst)
(list less same greater ))
((< (car lst) item)
(partition-iter (cdr lst)
(cons (car lst) less)
same
greater ))
((= (car lst) item)
(partition-iter (cdr lst)
less
(cons (car lst) same)
greater ))
(else ; (> (car lst) item) ; keep it here for documentation!
(partition-iter (cdr lst)
less
same
(cons (car lst) greater) )) ))
(partition-iter lst '() '() '()))
I don't even have to load it into DrRacket now to see that it's alright.
Symmetry is beautiful. Symmetry is right.
BTW, in a pattern-matching pseudocode with guards, it could be written as
partition lst item = partition-iter lst [] [] []
where
partition-iter [] less same greater = [less, same, greater]
partition-iter [a, ...lst] less same greater
| a < item = partition-iter lst [a, ...less] same greater
| a == item = partition-iter lst less [a, ...same] greater
| else = partition-iter lst less same [a, ...greater]
which I think is much more visually apparent. Going back and forth between it and the proper Scheme is a matter of purely syntactical transformations.