我试图检查两个列表是否有相同的元素。
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")
我完全输了,代码无法编译。
答案 0 :(得分:3)
您可以按照intersect
和null
定义此功能,如下所示:
compareList :: (Eq a) => [a] -> [a] -> Bool
compareList a = not . null . intersect a
您的代码未编译,因为:
result
list1
和list2
未在result
putStrnLn
不存在;你可能意味着putStrLn
compareList
中呼叫main
,其中Bool
,而不是IO ()
(Eq a) =>
以及compareList
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")
答案 1 :(得分:1)
如果没有显式递归,您可以使用此
compareList :: (Eq a) => [a] -> [a] -> Bool
compareList xs ys = foldl (\acc x -> x `elem` ys || acc) False xs