Skip to content

Commit

Permalink
Functors.
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabi Volpe committed Aug 17, 2016
1 parent 94e37d4 commit 2af9f91
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 0 deletions.
3 changes: 3 additions & 0 deletions category-theory/functor-example1.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
main = do line <- fmap reverse getLine
putStrLn $ "You said " ++ line ++ " backwards!"
putStrLn $ "Yes, you really said" ++ line ++ " backwards!"
5 changes: 5 additions & 0 deletions category-theory/functor-example2.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import Data.Char
import Data.List

main = do line <- fmap (intersperse '-' . reverse . map toUpper) getLine
putStrLn line
18 changes: 18 additions & 0 deletions category-theory/functors-module.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-- few examples on List, Mabe and Either
a1 = fmap (replicate 3) [1,2,3,4]
a2 = fmap (replicate 3) (Just 4)
a3 = fmap (replicate 3) (Right "blah")
a4 = fmap (replicate 3) Nothing
a5 = fmap (replicate 3) (Left "foo")

----------- functor laws in action

-- identity function (\x -> x). Formerly: fmap id = id
b1 = fmap id (Just 3)
b2 = id (Just 3)
b3 = fmap id [1..5]
b4 = id [1..5]
b5 = fmap id []
b6 = fmap id Nothing

-- composition: fmap (f . g) F = fmap f (fmap g F)
13 changes: 13 additions & 0 deletions category-theory/functors.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- Defined in the standard library
instance Functor IO where
fmap f action = do
result <- action
return (f result)

-- defined in Control.Monad.Instances
instance Functor ((->) r) where
fmap f g = (\x -> f (g x))

-- same as aboved using composition
instance Functor ((->) r) where
fmap = (.)
File renamed without changes.

0 comments on commit 2af9f91

Please sign in to comment.