检查2列表是否有任何相同的元素Haskell

时间:2014-12-14 17:02:20

标签: list haskell

我试图检查两个列表是否有相同的元素。

Example : 
List1 = ["John", "Thomas", "Sinclair", "Marie"]
List2 = ["Philip", "Albert", "Maria"]

结果应该是假的。

但如果是这样的话:

List3 = ["John", "Thomas", "Sinclair", "Marie"]
List4 = ["Philip", "Albert", "Marie", "Edward"]

结果应该是真的,list3和list4有相同的," Marie"。

我的代码:

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")

我完全输了,代码无法编译。

2 个答案:

答案 0 :(得分:3)

您可以按照intersectnull定义此功能,如下所示:

compareList :: (Eq a) => [a] -> [a] -> Bool
compareList a = not . null . intersect a

Live demo

您的代码未编译,因为:

  1. 您在result
  2. 的定义中有一个奇怪的缩进
  3. list1list2未在result
  4. 中定义
  5. putStrnLn不存在;你可能意味着putStrLn
  6. 您在compareList中呼叫main,其中Bool,而不是IO ()
  7. 您需要在(Eq a) =>以及compareList
  8. 中添加result约束

    如果你遵循这些建议,你会得到:

    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

答案 1 :(得分:1)

如果没有显式递归,您可以使用此

compareList :: (Eq a) => [a] -> [a] -> Bool
compareList xs ys = foldl (\acc x -> x `elem` ys || acc) False xs