0

我正在学习 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

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

4

1 回答 1

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 -> []
于 2014-03-16T17:22:13.130 回答