scheme - Trying to check if all elements of a list are unique -
as title suggest trying write scheme function checks if elements of list unique. have written code think should work:
(define are-all-unique? (lambda (v) (if (member (car v) (cdr v)) #f (if (pair? v) (are-all-unique? (cdr v)) #t))))
and works fine in case false, if write:
(are-all-unique? '(1 2 3))
it returns:
exception in car: () not pair
does have clue on how fix this, , doing wrong? :)
well, error message states, you're attempting pass empty list car
. why that's happening, let's take @ code.
as know, need pass cons
cell car
, cdr
them work. check property using pair?
, doing. problem when you're doing it.
the best way debug function trace through happens when pass bad input (in case '()
) function. first thing run test in if
statement: (member (car v) (cdr v))
. now, since input we're tracing empty list, fail every time. want more this:
;; are-all-equal? poor choice of function name, way, since that's ;; not function checks (define are-all-unique? (lambda (v) (if (pair? v) ; way branch ever execute ; if (pair? v) true, know (car v) , (cdr v) ; never raise exceptions (and (not (member (car v) (cdr v))) (are-all-unique? (cdr v))) #t)))
the thing note here control flow structure of version of function: proper list either cons
cell or empty list, have 2 cases in our function (one each possibility). when writing functions deal lists, 1 should (for part) decide want in nonempty , empty cases, , make sending list argument appropriate case first thing inside of function. such approach appropriate when doing structural recursion (i.e., in words of 1 of freshman professors, 'the structure of data informs structure of code').
Comments
Post a Comment