haskell - 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
?
解决方案
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
并用于“覆盖” Nothing
with (<|>)
。以下元素被忽略。对于last
,它大致相同,但翻转了。
推荐阅读
- javascript - 如何将整个 ViewModel 传递到 .net core mvc 3.1 中的外部 Javascript 文件中?
- macos - 如何使用旧代码库中的 Big-Sur 样式工具栏 + 拆分视图?
- clang - 找不到一些 Clang 命令行参数解释
- c# - 如何将 Visual c# 轨迹栏的值输入到笔大小值中?
- python-3.x - 如何使半径输入自动出现(Python 3)
- bash - 通过 azure cli 并行取消分配和调整 VM 的大小
- go - 本地版golang tour启动问题
- .net - 正则表达式捕获列中的多个单词
- go - 为什么默认 CGO_ENABLED=1?
- loops - 从循环宏进行递归调用