我正在学习Haskell,我现在和可能的班级一起做一个练习。我必须创建一个函数,该函数将f(“可能函数”)反复应用于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我的程序不像解决方案那样工作。也许我用错了“案例”,但我不确定。
发布于 2014-03-16 17:22:13
您对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 -> []https://stackoverflow.com/questions/22440092
复制相似问题