可以通过以下步骤实现:
isDuplicate :: Eq a => [a] -> a -> Bool
isDuplicate xs x = elem x xs
removeDuplicates :: Eq a => [a] -> [a]
removeDuplicates xs = foldl (\acc x -> if isDuplicate acc x then acc else acc ++ [x]) [] xs
在上述代码中,我们使用了匿名函数作为二元操作函数,它接受累积的结果列表(acc)和当前元素(x)作为参数。如果当前元素已经存在于结果列表中,则直接返回结果列表;否则,将当前元素添加到结果列表中。
main :: IO ()
main = do
let xs = [1, 2, 3, 2, 4, 1, 5, 6, 4]
let result = removeDuplicates xs
putStrLn $ "Original List: " ++ show xs
putStrLn $ "List without duplicates: " ++ show result
运行上述代码,将输出以下结果:
Original List: [1,2,3,2,4,1,5,6,4]
List without duplicates: [1,2,3,4,5,6]
这样,我们就成功地使用foldl删除了列表中的重复项。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云