Implementation of inits using foldr

两盒软妹~` 提交于 2019-12-01 22:15:58

问题


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:

  1. the base case z: what should inits [] be?
  2. the recursive step f: if you have a list xs == x:xs', how can you construct inits xs from x and y == inits xs'?

Working through some small examples on paper might help. e.g.

  • compute inits [1] recursively: you have x == 1 and y == inits [] == [[]] and need to get to [[], [1]].
  • compute inits [1, 2] recursively: you have x == 1 and y == 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!