为什么这两个Haskell“展开”功能不同?

时间:2014-03-16 17:14:20

标签: haskell functional-programming maybe

我正在学习Haskell,现在我正在使用Maybe Class进行练习。我必须创建一个函数,将f(“Maybe function”)重复应用于(及其后续结果),直到 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

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

1 个答案:

答案 0 :(得分:9)

您对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 -> []