简体   繁体   中英

Scheme Recursively going through a List

Just trying to get back into the swing of scheme again, because everyone loves recursion.. (mhhmnmm.)

anyways trying to return #t or #f to determine whether all elements in a list are unique.

Comparing 1st element and 2nd element no problem. It's recursively continuing..

(define (unique ls)
  (if (null? ls) #t
     (equal? (car ls)(car(cdr ls)))))

I'll write a different, simpler function that demonstrates looping. Hopefully between that and what you have, you'll get there. :-)

(define (member x lst)
  (cond ((null? lst) #f)
        ((equal? x (car lst)) lst)
        (else (member x (cdr lst)))))

Another example:

(define (assoc x alist)
  (cond ((null? alist) #f)
        ((equal? x (caar alist)) (car alist))
        (else (assoc x (cdr alist)))))

Well your (equal?) invocation is incomplete. If the head and head-of-the-tail are equal, then the value of "unique" is false . If they're not equal, then you'd return the value of unique as applied to the tail (cdr) of the list.

(It's implicit in your proto-implementation that you're checking a pre-sorted list. If not, then that's another step to take.)

(use srfi-1)

(define (unique? ls) (eq? (length ls) (length (delete-duplicates ls))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM