【问题标题】:Implementation of inits using foldr使用foldr实现init
【发布时间】:2014-06-09 10:52:33
【问题描述】:

我必须通过 foldr 使用 map 来实现初始化。我得到了大部分,但是我的结果列表中缺少空列表元素。

inits :: [a] -> [[a]]
inits = foldr ( \ x y -> [x] : (map (x:) y) ) []

调用时会导致:

*蓝图

[[1],[1,2],[1,2,3]]

我现在有点卡住了,如果有人能指出我错误的大致方向,我会很高兴。

提前致谢

已解决:

inits :: [a] -> [[a]]
inits = foldr ( \ x y -> [] : (map (x:) y) ) [[]]

【问题讨论】:

    标签: haskell fold


    【解决方案1】:

    要使用foldr f z 编写内容,您需要考虑两件事:

    1. 基本情况zinits [] 应该是什么?
    2. 递归步骤f:如果你有一个列表xs == x:xs',你如何从xy == inits xs'构造inits xs

    在纸上研究一些小例子可能会有所帮助。例如

    • 递归计算inits [1]:你有x == 1y == inits [] == [[]],需要到达[[], [1]]
    • 递归计算inits [1, 2]:你有x == 1y == inits [2] == [[], [2]],需要到达[[], [1], [1, 2]]

    【讨论】:

    • 谢谢,在对上述方向进行了更多思考后,我明白了:)
    【解决方案2】:

    更紧凑的解决方案:

    inits :: [a] -> [[a]]
    inits = foldr ((([] :) .) . map . (:)) [[]]
    

    【讨论】:

    • 神圣的标点符号,蝙蝠侠!不幸的是,我们的教授要求我们将上述模式用于该功能:D
    猜你喜欢
    • 2010-09-19
    • 2013-03-30
    • 2016-09-04
    • 2021-04-15
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多