【问题标题】:Why are these two Haskell "unfold" functions different?为什么这两个 Haskell “展开”功能不同?
【发布时间】:2018-02-12 01:12:03
【问题描述】:

我正在学习 Haskell,现在我正在使用 Maybe 类做一个练习。我必须创建一个函数,将 f("Maybe function") 重复应用于 a(及其以下结果),直到 f a 返回 Nothing。 例如 f a0 = Just a1,f a1= Just a2,...,f an = Nothing。那么

unfold f a0 = [a0,a1,...,an]

我已经尝试过,并且我得到了:

unfold :: (a- > Maybe a) -> a -> [a]
unfold f a = case f a of
                 Just n -> n: unfold f a
                 Nothing -> []

问题在于解决方法是:

unfold' :: ( a -> Maybe a) -> a -> [a]
unfold' f a = a : rest ( f a )
     where rest Nothing = []
           rest ( Just x ) = unfold' f x

而且我的程序不像解决方案那样工作。也许我使用了错误的“case of”,但我不确定。

【问题讨论】:

  • Maybe 不是一个类,它是一种数据类型。

标签: haskell functional-programming maybe


【解决方案1】:

您对case 的使用很好,但请查看您在列表中的哪些地方使用了新值,以及解决方案在哪里使用。

testFunc = const Nothing

unfold  testFunc 1 == []  -- your version prepends only if f a isn't Nothing
unfold' testFunc 1 == [1] -- the solution _always_ prepends the current value

另外,你一直在使用相同的值。

unfold :: (a -> Maybe a) ->a -> [a]
unfold f a = a : case f a of -- cons before the case
    Just n  -> unfold f n    -- use n as parameter for f
    Nothing -> []

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 2015-12-07
    • 2012-08-26
    • 1970-01-01
    相关资源
    最近更新 更多