In Programming in Haskell, Graham Hutton defines an unfold for lists as follows:
unfold :: (b -> Bool ) -> (b -> a) -> (b -> b) -> b -> [a]
unfold p h t x | p x = []
| otherwise = h x : unfold p h t (t x)
Define a function
• listUnfold :: (b -> Bool) -> (b -> a) -> (b -> b) -> b -> [a]
that is similar to the one above but uses unfoldr in its implementation and is non-recursive.
I've been trying for a while to solve the question above but I still can manage to do so (pretty new in Haskell and functional programming in general).
My attempt:
listUnfold :: (b -> Bool) -> (b -> a) -> (b -> b) -> b -> [a]
listUnfold f h t x
| f x == True = []
| otherwise = h x :
listUnfoldr (\x -> if f x then Nothing else Just ((h x), (t x))) x
In english, if f x
is true, return the empty list. Otherwise, use h x
as the head and append the results of unfoldr as the tail. Unfoldr takes a list (x:xs)
should recurse itself with x
as the head and xs
as the tail.
p/s: I'm probably doing this very very wrongly.
t
at all. – hammar