Functor fmap: how to

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Functor fmap: how to

Imants Cekusins
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
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: Functor fmap: how to

Imants Cekusins
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
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: Functor fmap: how to

Imants Cekusins
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
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: Functor fmap: how to

Imants Cekusins
.. 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
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners