user3645265
user3645265

Reputation: 773

Checking if 2 list have any equal element Haskell

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

Answers (2)

Shoe
Shoe

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

Live demo

Your code is not compiling because:

  1. you have a weird indentation in the definition of result
  2. list1 and list2 are not defined within result
  3. putStrnLn doesn't exist; you probably meant putStrLn
  4. you are calling compareList in main, which returns Bool, not IO ()
  5. you need to add an (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")

Live demo

Upvotes: 3

Simon H
Simon H

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

Related Questions