gpt4 book ai didi

list - 在 Haskell 中完全消除重复项

转载 作者:行者123 更新时间:2023-12-03 20:27:32 25 4
gpt4 key购买 nike

我有这个代码,但它完全没有做我想要的,我需要一个元组列表;

[(3,2),(1,2),(1,3),(1,2),(4,3),(3,2),(1,2)]

并给
[(1,3),(4,3),(3,2),(1,2)]

但我希望它给予
[(1,3),(4,3)]

我哪里做错了?提前致谢。
eliminate :: [(Int,Int)] -> [(Int,Int)]
eliminate [] = []
eliminate (x:xs)
| isTheSame xs x = eliminate xs
| otherwise = x : eliminate xs


isTheSame :: [(Int,Int)] -> (Int,Int) -> Bool
isTheSame [] _ = False
isTheSame (x:xs) a
| (fst x) == (fst a) && (snd x) == (snd a) = True
| otherwise = isTheSame xs a

最佳答案

代码几乎是正确的。只需改变这一行

    | isTheSame xs x  = eliminate xs


    | isTheSame xs x  = eliminate $ filter (/=x) xs   

原因是如果 x包含在 xs ,要删除所有出现的 x .

也就是说,您的代码示例中有几个部分可以更优雅地表达:
  • (fst x) == (fst a) && (snd x) == (snd a)x == a 相同
  • isTheSameelem 相同, 只是它的参数颠倒了

  • 因此,我们可以表达函数 eliminate像这样:
    eliminate [] = []
    eliminate (x:xs)
    | x `elem` xs = eliminate $ filter (/=x) xs
    | otherwise = x : eliminate xs

    关于list - 在 Haskell 中完全消除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15771882/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com