Programming in Scheme: Count Distinct Elements

Below is a simple program developed in the Scheme programming language to illustrate how functional languages operate. This particular program will count the number of distinct elements in a list. See if you can understand the functional logic behind the program.


(define count-dist-elements
  (lambda (lis)
    (cond
      ( (null? lis) 0)
      ( (member (car lis) (cdr lis))
        (+ 0 (count-dist-elements (cdr lis)))
      )
      (else
        (+ 1 (count-dist-elements (cdr lis)))
      )
    )
  )
)

(count-dist-elements '(1 2 1 1 2 3 4 5 5 6 6 7 7 8 8 8 9 10 11 11 12 10 13))

When run, the output is:

13
>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>