Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two lists in Racket

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?

like image 924
Elik Avatar asked Oct 28 '25 04:10

Elik


1 Answers

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
like image 139
svk Avatar answered Oct 30 '25 01:10

svk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!