Reputation: 23
I'm trying to become more familiar with recursion in Scheme. I have searched the question bank and see many "built-in" functions for finding duplicate entries in a scheme list, but am trying to design my own. I have not learned about "lambda" yet either. My concern is when I call the recursion function, the car element will be updated. I wish to keep it the same, but pass a new cdr each time, so the original car element can be compared against each subsequent element in the list. I want to return a #t if there is a match, and #f if there is no match or the cdr is empty (base case). Any help/advice would be greatly appreciated.
(define (findDuplicates list)
(if (null? list)
#f
(if (null? (cdr list))
#f
(if (= (car list) (getCarOfCdr list))
#t
(findDuplicates (cdr list)) //trying to use recursion
)
)
)
)
(define (getCarOfCdr list) //Helper function
(car (cdr list))
)
Upvotes: 0
Views: 2841
Reputation: 235984
You should use at least one built-in procedure to make things simpler: member
(which is standard). Some general suggestions:
list
, that clashes with a built-in function with the same name.if
s like that, use cond
instead.getCarOfCdr
is not necessary: it can be replaced by a call to cadr
and besides, that won't work: you have to check each element against all the rest of the list - that's why you should use member
.Taking all of the above suggestions into consideration, here's my proposed solution:
(define (findDuplicates lst)
(cond ((null? lst) #f)
((member (car lst) (cdr lst)) #t)
(else (findDuplicates (cdr lst)))))
If using member
doesn't satisfy your requirements, then it's easy to implement, and simpler than findDuplicates
; you should try to write your own version, just for fun.
Upvotes: 3