繁体   English   中英

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

[英]Why are these two Haskell “unfold” functions different?

我正在学习Haskell,现在正在与Maybe Class一起练习。 我必须创建一个将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”,但是我不确定。

使用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 -> []

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM