首页 > 解决方案 > Finding head of a list using foldl and the last element using foldr

问题描述

It is known that we can find head of a list using foldr like this:

head'' :: [a] -> a
head'' = foldr (\x _ -> x) undefined

but, is there any way to get the same result using foldl?

Similarly, we can find the last element of list using foldl like this:

last'' :: [a] -> a
last'' = foldl (\_ x -> x) undefined

Is there any way to get the same result using foldr?

标签: haskellfold

解决方案


head不能用 编写foldl,因为foldl在无限列表上进入无限循环,而head不会。否则,确定:

head' :: [a] -> a
head' = fromJust . foldl (\y x -> y <|> Just x) Nothing

删除fromJust安全版本。

last绝对可以写成 a foldr,大致相同:

last' :: [a] -> a
last' = fromJust . foldr (\x y -> y <|> Just x) Nothing

对于head,我们从 开始Nothing。第一个元素(想要的元素)被包裹Just并用于“覆盖” Nothingwith (<|>)。以下元素被忽略。对于last,它大致相同,但翻转了。


推荐阅读