[Haskell-beginners] Functor fmap: how to

Imants Cekusins imantc at gmail.com
Wed Jun 24 19:52:37 UTC 2015


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:Functor

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


More information about the Beginners mailing list