简体   繁体   中英

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

I have heard the 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:

在此处输入图像描述

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 'sset 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"]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM