使用foldr实现inits [英] Implementation of inits using foldr

查看:119
本文介绍了使用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 来编写一些东西,你需要考虑两件事情:


  1. 基本情况 z :应该 inits如果你有一个列表

  2. 递归步骤 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:

    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]].

    这篇关于使用foldr实现inits的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆