
There are a few Functor & fmap tutorials. Here is basic use of fmap. If it leaves you confused, please ignore it. module FunctorFmap where {- why maybe & list? Functor instances exist for Maybe & List http://hackage.haskell.org/package/base-4.8.0.0/docs/Data-Functor.html#t:Fun... expand "instances" -} -- (a -> b) add3:: Int -> Int add3 = (+ 3) -- maybe runMaybe::IO () runMaybe = do print $ maybeFmap $ Just 1 print $ maybeInfixed $ Just 1 print $ maybeFmap Nothing print $ maybeInfixed Nothing -- maybeFmap & maybeInfixed do the same thing. different syntax maybeFmap::Maybe Int -> Maybe Int maybeFmap = fmap add3 maybeInfixed::Maybe Int -> Maybe Int maybeInfixed mi = add3 <$> mi -- list runList::IO () runList = do print $ listFmap [1,2] print $ listInfixed [1,2] -- listFmap & listInfixed do the same thing. different syntax listFmap::[Int] -> [Int] listFmap = fmap add3 listInfixed::[Int] -> [Int] listInfixed l = add3 <$> l

as the author just realized :-P, we can fmap (a -> b), too module FunctorAb where -- (a -> b) overTen:: Int -> Bool overTen x | x > 10 = True | otherwise = False -- maybe maybe1::Maybe Int -> Maybe Bool maybe1 mi = overTen <$> mi -- list list1::[Int] -> [Bool] list1 l = overTen <$> l

a Functor instance is defined for IO, so we can fmap (a -> b) over IO, too. not using IO monad it seems ;) module FunctorIO where {- usage: *FunctorIO> main {type something, <enter>} -} process:: String -> String process s = s ++ " .. ok" main::IO String main = func getLine func::IO String -> IO String func ios = process <$> ios

.. and an a -> b version: module FunctorIOab where {- usage: *FunctorIOab> main {type something, <enter>} -} processAb:: String -> Int processAb = length main::IO Int main = func getLine func::IO String -> IO Int func ios = processAb <$> ios
participants (1)
-
Imants Cekusins