问题
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) ) [[]]
回答1:
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 xsfromxandy == inits xs'?
Working through some small examples on paper might help. e.g.
- compute
inits [1]recursively: you havex == 1andy == inits [] == [[]]and need to get to[[], [1]]. - compute
inits [1, 2]recursively: you havex == 1andy == inits [2] == [[], [2]]and need to get to[[], [1], [1, 2]].
回答2:
A more compact solution:
inits :: [a] -> [[a]]
inits = foldr ((([] :) .) . map . (:)) [[]]
来源:https://stackoverflow.com/questions/24118741/implementation-of-inits-using-foldr