Schierke
Schierke

Reputation: 13

Finding duplicate elements in a Scheme List using recursion

I'm trying to create a function that will check a list of numbers for duplicates and return either #t or #f. I can only use car, cdr and conditionals, no cons. This is what I have so far but it's giving me the error "car: contract violation expected: pair? given: #f"

(define (dups a)
    (if (null? a)
        #f
        (if (= (car a)(car(dups(cdr a))))
            #t
            (dups (cdr))
        )
    )
)

I'm new to both scheme and recursion, any help/advice would be greatly appreciated.

Upvotes: 1

Views: 364

Answers (1)

Neowizard
Neowizard

Reputation: 3017

Your second if doesn't make much sense. I'm assuming you wanted to check whether (car a) appears somewhere further down the list, but (car (dups (cdr a))) doesn't give you that. Also, (car (dups ...)) is a type-issue since dups will return a boolean instead of a list, and car is expecting a list (or actually, a pair, which is what lists are composed of).

What you need is a second function to call in the test of that second if. That function takes an element and a list and searches for that element in the list. Of course, if you're allowed, use find, otherwise implement some sort of my-find - it's quite simple and similar to your dups function.

Upvotes: 0

Related Questions