更新时间:2022-10-22 08:49:10
一种低效率的方式是
intersect'xs ys = xs \\(xs \\ ys)
例如
[1,2,2,2,3,4] \\\ [6,4,4, 2,2] == [1,2,3]
[1,2,2,2,3,4] \\ [1,2,3] == [2,2,4]
和
[6,4,4,2,2] \\ [1,2,2,2,3,4] == [6,4]
[6,4,4, 2,2] \\ [6,4] == [4,2,2]
从 http://hackage.haskell.org/package/base-4.7。 0.1 / docs / Data-List.html :
在 xs \\ ys $ c $的结果中c>,首先出现
ys
的每个元素(如果有)已从 xs
中删除。因此
(xs ++ ys)\\ xs == ys。
I am new to Haskell and this has to be quite simple, but I have been searching the net for an hour without finding a convenient answer.
What I want is a function that returns an 'intersection' of two lists: a list of the elements that exists in both lists, taking account of duplicates.
I thought the function intersect
would be what I wanted but, as stated in the docs, if the first list contains duplicates, so will the result. E.g.:
[1,2,2,2,3,4] `intersect` [6,4,4,2,2] == [2,2,2,4]
This is not what I want, since [2,2,2,4] isn't a part of [6,4,4,2,2] because there are only two 2's in that list. My desired result is:
[1,2,2,2,3,4] `intersect` [6,4,4,2,2] == [2,2,4]
How could this be accomplished?
One inefficient way is
intersect' xs ys = xs \\ (xs \\ ys)
For example
[1,2,2,2,3,4] \\ [6,4,4,2,2] == [1,2,3]
[1,2,2,2,3,4] \\ [1,2,3] == [2,2,4]
And
[6,4,4,2,2] \\ [1,2,2,2,3,4] == [6,4]
[6,4,4,2,2] \\ [6,4] == [4,2,2]
From http://hackage.haskell.org/package/base-4.7.0.1/docs/Data-List.html :
In the result of xs \\ ys
, the first occurrence of each element of ys
in turn (if any) has been removed from xs
. Thus
(xs ++ ys) \\ xs == ys.