开发者

Scheme Recursively going through a List

开发者 https://www.devze.com 2023-02-06 19:53 出处:网络
Just trying to get back into the swing of scheme again, because everyone loves recursion.. (mhhmnmm.)

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 elem开发者_如何学Cent 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))))
0

精彩评论

暂无评论...
验证码 换一张
取 消