I'm trying to write a function wich given two lists returns a boolean responding if the two lists have the same elements, even if they do not appear in the same order. I've got something like this:
function :: [a] -> [a] -> Bool
function (x:xs) y = elem x y && function xs y
The problem with this is that there's no pattern when xs is empty, and I do not have any idea how to deal with that case. Any other way to solve this will be really welcome, I am quite new to Haskell.
Thanks all!
Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets. If they have some common elements then the new set will not be empty.
Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets.
You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.
This works as well
import Data.List
function :: (Eq a) => [a] -> [a] -> Bool
function x y = null (x \\ y) && null (y \\ x)
Use the clause:
function [] y = True
All the elements of the empty list are in the list y
.
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