使用foldr实现inits [英] Implementation of inits using foldr
本文介绍了使用foldr实现inits的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须通过使用map的foldr实现inits。我得到了大部分,但是我的结果列表中缺少空列表元素。
inits :: [a] - > [[a]]
inits = foldr(\ xy - > [x]:(map(x :) y))[]
当调用此结果时:
*蓝图< inits [1,2,3]
[[1],[1,2],[1,2,3]]
现在我有点被卡住了,如果有人能指出我的错误的大方向,我会很高兴。
预先感谢
解决:
inits :: [a] - > [[a]]
inits = foldr(\ xy - > []:(map(x :) y))[[]]
解决方案使用
foldr fz
来编写一些东西,你需要考虑两件事情: - 基本情况
z
:应该inits如果你有一个列表
- 递归步骤
f
> xs == x:xs',你如何从x
构造inits xs
$ b
$ b $ b通过纸上的一些小例子可能会有所帮助。例如
- 计算
inits [1]
递归:您有x == 1
和y == inits [] == [[]]
并且需要到达[ [],[1]]
。 - 递归地计算
inits [1,2]
x == 1
和y == inits [2] == [[],[2]]
并且需要转到[[],[1],[1,2]]
。
I have to implement inits via foldr using map. I got most of it, however I'm missing the empty list element in my result list.
inits :: [a] -> [[a]] inits = foldr ( \ x y -> [x] : (map (x:) y) ) []
When called this results in:
*Blueprint< inits [1,2,3]
[[1],[1,2],[1,2,3]]
I am a bit stuck now and would be glad if someone could point me in the general direction of my error.
Thanks in advance
Solved:
inits :: [a] -> [[a]] inits = foldr ( \ x y -> [] : (map (x:) y) ) [[]]
解决方案To write something with
foldr f z
you need to think about two things:- the base case
z
: what shouldinits []
be? - the recursive step
f
: if you have a listxs == x:xs'
, how can you constructinits xs
fromx
andy == inits xs'
?
Working through some small examples on paper might help. e.g.
- compute
inits [1]
recursively: you havex == 1
andy == inits [] == [[]]
and need to get to[[], [1]]
. - compute
inits [1, 2]
recursively: you havex == 1
andy == inits [2] == [[], [2]]
and need to get to[[], [1], [1, 2]]
.
这篇关于使用foldr实现inits的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 计算
查看全文