开发者

Can't seem to get my head around the 'list difference' (\\) operator

I have heard th开发者_StackOverflow中文版e term 'list difference' (\\) operator in Haskell but still don't quite know how to get my head around it. Any examples or ideas?


The (\\) operator (and the difference function) implements set difference, so, if you have two lists, a and b, it returns only those elements of a that are not in b, as illustrated:

Can't seem to get my head around the 'list difference' (\\) operator


Simply put, it takes two lists, goes through the second and for each item, removes the first instance of the same item from the first list.

> [1..10] \\ [2, 3, 5, 8]
[1,4,6,7,9,10]
> [1, 2, 1, 2, 1, 2] \\ [2]
[1,1,2,1,2]
> [1, 2, 1, 2, 1, 2] \\ [2, 2]
[1,1,1,2]
> [1, 2, 1, 2, 1, 2] \\ [2, 2, 1]
[1,1,2]


xs \\ ys is all the elements in xs that are not in ys. Maybe a list comprehension will clarify this:

xs \\ ys = [ x | x <- xs, x `notElem` ys ]

or, if you could do this in Haskell,

xs \\ ys = [ x | x `elem` xs, x `notElem` ys ]

This comes from set theory's set difference. The basic idea is that you are "subtracting" one collection of elements from another, hence the term "difference".


Suppose, you have a list of things, for example cities. Let's take for instance this list:

a = ["London","Brussels","Tokio","Los Angeles","Berlin","Beijing"]

Now you want to remove all cities that are in Europe. You know, that those cities are in Europe:

b = ["Glasgow","Paris","Bern","London","Madrid","Amsterdam","Berlin","Brussels"]

To get a list of cities in a, that are not in Europe, so that are not in b, you can use (\\):

a \\ b = ["Tokio","Los Angeles","Beijing"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜