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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With