Reputation: 773
I was trying to check if two lists have some equal element.
Example :
List1 = ["John", "Thomas", "Sinclair", "Marie"]
List2 = ["Philip", "Albert", "Maria"]
The result should be false.
But if was like this :
List3 = ["John", "Thomas", "Sinclair", "Marie"]
List4 = ["Philip", "Albert", "Marie", "Edward"]
The result should be true, list3 e list4 have the same, "Marie".
My code :
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
main = do
list1 <- fmap Text.lines (Text.readFile "file1.txt")
list2 <- fmap Text.lines (Text.readFile "file.txt")
compareList list1 list2
compareList (x:xs) ys | elem x ys = True
|otherwise = compareList xs ys
result =
if ((compareList list1 list2) == True)
then putStrnLn ( " They sare elements")
else
putStrnLn ("They don't share elements")
I'm totally lost, the code does not compile.
Upvotes: 2
Views: 3405
Reputation: 76240
You can define this function in terms of intersect
and null
as follows:
compareList :: (Eq a) => [a] -> [a] -> Bool
compareList a = not . null . intersect a
Your code is not compiling because:
result
list1
and list2
are not defined within result
putStrnLn
doesn't exist; you probably meant putStrLn
compareList
in main
, which returns Bool
, not IO ()
(Eq a) =>
constraint on compareList
as well as in result
If you follow these suggestions you get:
compareList :: (Eq a) => [a] -> [a] -> Bool
compareList [] _ = False
compareList (x:xs) ys
| elem x ys = True
| otherwise = compareList xs ys
result :: (Eq a) => [a] -> [a] -> IO ()
result list1 list2 =
if (compareList list1 list2)
then putStrLn ("They share elements")
else putStrLn ("They don't share elements")
Upvotes: 3
Reputation: 21005
Without explicit recursion, you could use this
compareList :: (Eq a) => [a] -> [a] -> Bool
compareList xs ys = foldl (\acc x -> x `elem` ys || acc) False xs
Upvotes: 1