Comparing two lists in Racket

11,323

If the number of occurrences doesn't matter, you're doing set comparison. You can convert the lists to sets and then compare the sets:

> (equal? (list->set '(1 2 3 4 5)) (list->set '(5 4 3 2 1)))
#t

If the number of occurrences does matter, you're doing multiset comparison. A simple way to do this for common kinds of values is to sort both lists, and then compare them for equality in the usual way:

> (equal? (sort '(3 2 1 4 5) <) (sort '(2 1 3 4 5) <))
#t
> (equal? (sort '(1 2 1) <) (sort '(2 1) <))
#f
Share:
11,323
Elik
Author by

Elik

Updated on June 08, 2022

Comments

  • Elik
    Elik almost 2 years

    Is there a built-in function in Racket that we can check the equality of two lists in terms of only values and not the order of the values, with?

    For example, it should return true if you compare '(1 2 2 3 4 5) with '(3 1 2 5 4).

    Or what is the easiest way to implement such a function?