Search code examples
haskellfunctional-programminghaskell-platform

Haskell: Defining map function using unfold


I have the following Haskell method

unfold :: (a -> Bool) -> (a -> b) -> (a -> a) -> a -> [b]
unfold p h t x
    | p x       = []
    | otherwise = (h x):(unfold p h t (t x))

How can i define the regular prelude map f x method using this given unfold method.


Solution

  • If you define:

    map' :: (a -> b) -> [a] -> [b]
    map' f = unfold null (f.head) tail
    

    then

    \> map' show [1..5]
    ["1","2","3","4","5"]
    \> map' (+1) []
    []