Code: Select all
(define filter
(lambda (fn values)
"This function is a tail recursive implementation of the filter function
found in other Lisp dialect."
(let loop ((v values)
(rest '()))
(let ((item (car v))
(next (cdr v))) ; Saves car and cdr for efficiency.
(if (fn item)
;; Add the current 'item to 'rest if 'fn returned #t, then continue
;; though the list. Return 'this AND 'rest revsered.
(if (pair? next)
(loop next (cons item rest))
(reverse (cons item rest)))
;; Don't add the 'item to the 'rest list but continue on though the
;; list.
(if (pair? next)
(loop next rest)
(reverse rest)))))))
Code: Select all
> (filter even? '(1 2 3 4 5 6 7))
(2 4 6)
Any tips or insight you could give would be more welcome than you know.
I'm currently thinking about how to do reduce but I'm not so sure how it works to he honest, it's not something I've used much before recently.
EDIT: Please forgive the text-wrapping on the comments.
Thanks in advance,
Mark.