From 2af9f911ecf6b64fad8afbf1730803f40973d762 Mon Sep 17 00:00:00 2001 From: Gabi Volpe Date: Wed, 17 Aug 2016 16:39:04 +0100 Subject: [PATCH] Functors. --- category-theory/functor-example1.hs | 3 +++ category-theory/functor-example2.hs | 5 +++++ category-theory/functors-module.hs | 18 ++++++++++++++++++ category-theory/functors.hs | 13 +++++++++++++ paths.txt => problems/paths.txt | 0 5 files changed, 39 insertions(+) create mode 100644 category-theory/functor-example1.hs create mode 100644 category-theory/functor-example2.hs create mode 100644 category-theory/functors-module.hs create mode 100644 category-theory/functors.hs rename paths.txt => problems/paths.txt (100%) diff --git a/category-theory/functor-example1.hs b/category-theory/functor-example1.hs new file mode 100644 index 0000000..a3615fa --- /dev/null +++ b/category-theory/functor-example1.hs @@ -0,0 +1,3 @@ +main = do line <- fmap reverse getLine + putStrLn $ "You said " ++ line ++ " backwards!" + putStrLn $ "Yes, you really said" ++ line ++ " backwards!" diff --git a/category-theory/functor-example2.hs b/category-theory/functor-example2.hs new file mode 100644 index 0000000..762a6ce --- /dev/null +++ b/category-theory/functor-example2.hs @@ -0,0 +1,5 @@ +import Data.Char +import Data.List + +main = do line <- fmap (intersperse '-' . reverse . map toUpper) getLine + putStrLn line diff --git a/category-theory/functors-module.hs b/category-theory/functors-module.hs new file mode 100644 index 0000000..a7760fa --- /dev/null +++ b/category-theory/functors-module.hs @@ -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) diff --git a/category-theory/functors.hs b/category-theory/functors.hs new file mode 100644 index 0000000..1277df6 --- /dev/null +++ b/category-theory/functors.hs @@ -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 = (.) diff --git a/paths.txt b/problems/paths.txt similarity index 100% rename from paths.txt rename to problems/paths.txt