Gni*_*ruT 0 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]
Run Code Online (Sandbox Code Playgroud)
我试过这样做而且我得到了:
unfold :: (a- > Maybe a) -> a -> [a]
unfold f a = case f a of
Just n -> n: unfold f a
Nothing -> []
Run Code Online (Sandbox Code Playgroud)
问题是解决方案是:
unfold' :: ( a -> Maybe a) -> a -> [a]
unfold' f a = a : rest ( f a )
where rest Nothing = []
rest ( Just x ) = unfold' f x
Run Code Online (Sandbox Code Playgroud)
而我的程序不像解决方案那样工作.也许我使用了错误的"案例",但我不确定.
您的使用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
Run Code Online (Sandbox Code Playgroud)
此外,您始终使用相同的值.
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 -> []
Run Code Online (Sandbox Code Playgroud)