I'm learning Haskell and I'm doing now an exercise with the Maybe Class. I have to create a function which applies f("Maybe function") to a(and its following results) repeatedly until f a returns Nothing
. For example f a0 = Just a1,f a1= Just a2,...,f an = Nothing. Then
unfold f a0 = [a0,a1,...,an]
I've tried to do it and and I've got:
unfold :: (a- > Maybe a) -> a -> [a]
unfold f a = case f a of
Just n -> n: unfold f a
Nothing -> []
The problem is that the solution is:
unfold' :: ( a -> Maybe a) -> a -> [a]
unfold' f a = a : rest ( f a )
where rest Nothing = []
rest ( Just x ) = unfold' f x
And my program doesn't work like the solution. Maybe I'm using wrong "case of" but I'm not sure.
Your use of case
is fine, but have a look where you cons the new value on the list, and where the solution does.
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
Also, you're using the same value all the time.
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 -> []
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.