iterate f == unfoldr (\x -> Just (x, f x))In some cases, unfoldr can undo a foldr operation:
unfoldr f' (foldr f z xs) == xsif the following holds:
f' (f x y) = Just (x,y) f' z = Nothing
>>> take 1 (unfoldr (\x -> Just (x, undefined)) 'a') "a"
>>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10 [10,9,8,7,6,5,4,3,2,1]
>>> take 10 $ unfoldr (\(x, y) -> Just (x, (y, x + y))) (0, 1) [0,1,1,2,3,5,8,13,21,54]
unfoldr (\x -> if x <= 5 then Just (x, x + 1) else Nothing) 0 == pack [0, 1, 2, 3, 4, 5]
unfoldr (\x -> if x <= '9' then Just (x, succ x) else Nothing) '0' == "0123456789"
unfoldr (\x -> if x <= 5 then Just (x, x + 1) else Nothing) 0 == pack [0, 1, 2, 3, 4, 5]
unstream . unfoldr f z = unfoldr f z
unfoldr next = id
iterate f == unfoldr (\x -> Just (x, f x))In some cases, unfoldr can undo a foldr operation:
unfoldr f' (foldr f z xs) == xsif the following holds:
f' (f x y) = Just (x,y) f' z = NothingA simple use of unfoldr:
>>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10 [10,9,8,7,6,5,4,3,2,1]Laziness:
>>> take 1 (unfoldr (\x -> Just (x, undefined)) 'a') "a"
>>> S.stdoutLn $ S.take 2 $ S.unfoldr Pipes.next Pipes.stdinLn hello<Enter> hello goodbye<Enter> goodbye
>>> S.stdoutLn $ S.unfoldr Pipes.next (Pipes.stdinLn >-> Pipes.take 2) hello<Enter> hello goodbye<Enter> goodbye
>>> S.effects $ S.unfoldr Pipes.next (Pipes.stdinLn >-> Pipes.take 2 >-> Pipes.stdoutLn) hello<Enter> hello goodbye<Enter> goodbyePipes.unfoldr S.next similarly unfolds a Pipes.Producer from a stream.
iterate f == unfoldr (\x -> Just (x, f x))In some cases, unfoldr can undo a foldr operation:
unfoldr f' (foldr f z xs) == xsif the following holds:
f' (f x y) = Just (x,y) f' z = NothingA simple use of unfoldr:
>>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10 [10,9,8,7,6,5,4,3,2,1]