Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove common elements between two lists of strings in Haskell?

Tags:

haskell

I am a beginner to Haskell. I want to compare two lists of strings and remove the common elements between the lists and return a new list with unique elements.

Below is the code that I have:

Prelude Data.List> let list_1 = ["apple", "orange", "apple"]
Prelude Data.List> let list_2 = ["apple"]
Prelude Data.List> let removeCommonWords  xs ys = filter (\x -> x `elem` ys) xs
Prelude Data.List> removeCommonWords list_1 list_2

output of the above code:

["apple","apple"]

Currently, the filter function is filtering the common words and returning a new list that contains the common words. However, I want it to return a new list that contains the unique words. I think I will need a new regex expression for the filter function.

Expected output:

["orange"]

I also attempted the following:

Prelude Data.List> let removeCommonWords  xs ys = filter (\x -> x `elem` ys) xs
Prelude Data.List> remove ["orange", "apple", "apple"] "apple" 

The output of the above code is:

["orange"]

However, I want to compare two lists of strings - not a list and string.

like image 748
Big Smile Avatar asked Jan 29 '23 23:01

Big Smile


1 Answers

I think that is what you want

let removeCommonWords  xs ys = filter (\x -> not (x `elem` ys)) xs

Edit: You can also use notElem directly as:

let removeCommonWords  xs ys = filter (\x -> x `notElem` ys) xs
like image 190
ndrwnaguib Avatar answered May 23 '23 08:05

ndrwnaguib