Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the justification for the type of unfoldr in Haskell?

The example given in the documentation of unfoldr :: (b -> Maybe (a, b)) -> b -> [a]:

unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10

can easily be written with a redundant pair:

unfoldr (\b -> if b == 1 then Nothing else Just (b-1, b-1)) 11

What does unfoldr need the pair (a,b) for? Why is its type not (a -> Maybe a) -> a -> [a]?

like image 913
hkBst Avatar asked Dec 02 '22 15:12

hkBst


1 Answers

A function with type

(a -> Maybe a) -> a -> [a]

restricts the output list element type to be the same as the state which is threaded through the generation process. unfoldr is more general in that it allows an independent type of state to be used.

like image 65
Lee Avatar answered Feb 24 '23 21:02

Lee