Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme: How to check if all elements of a list are identical

I'd like to create a Scheme function that yields true if it is passed a list that is composed entirely of identical elements. Such a list would be '(1 1 1 1). It would yield false with something like '(1 2 1 1).

This is what I have so far:

    (define (list-equal? lst)
      (define tmp (car lst))
      (for-each (lambda (x) 
                   (equal? x tmp))
                 lst)
      )

Clearly this is incorrect, and I'm new to this. I guess I'm unable to express the step where I'm supposed to return #t or #f.

Thanks in advance!

EDIT: I fiddled a bit and found a solution that seems to work very well, and with a minimal amount of code:

(define (list-equal? lst)
 (andmap (lambda (x) 
        (equal? x (car lst)))
      lst))

Thanks again for the help everyone.

like image 372
Joseph Avatar asked Sep 06 '11 13:09

Joseph


1 Answers

Minimal amount of code, if you don't care that it only works for numbers:

(define (list-equel? lst)
  (apply = lst))

Examples:

> (list-equel? '(1 1 2 1))
#f
> (list-equel? '(1 1 1 1))
#t
> (list-equel? '(1))
#t
like image 187
andrykonchin Avatar answered Oct 13 '22 05:10

andrykonchin