In Haskell, how can you compare two lists to check if they are equal? Also the order shouldn't matter.
Example:
[1,2] = [2,1]
I tried all (flip elem [1,2,3]) [2,1]
, but this returns true
...
Thanks.
Something like this?
import Data.List (sort)
areEqual a b = sort a == sort b
OUTPUT:
*Main> areEqual [1,2] [2,1]
True
As Eq a => Eq [a]
( http://www.haskell.org/ghc/docs/7.4.1/html/libraries/base-4.5.0.0/Data-Eq.html )
you DON'T need extra code to compare lists for equality.
[1,2] == [2,1]
If you want to compare lists as bags, then a bag is a MultiSet , so look for a Multiset package
import "multiset" Data.MultiSet as M
-- or
import "multiset" Data.IntMultiSet as M -- if you deal with Ints
M.fromList [1,2] == M.fromList [2,1]
A good data structure for "collection without order or repetitions" is from the module Data.Set
:
import qualified Data.Set as S
sameElems xs ys = S.fromList xs == S.fromList ys
This does, however, consider [1,1]
to be equal to [1]
, which may not be what you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.