Skip to content

Instantly share code, notes, and snippets.

@pmcgee69
Last active April 19, 2021 21:21
Show Gist options
  • Save pmcgee69/4f6ddd6b1b971411236f56f36057067b to your computer and use it in GitHub Desktop.
Save pmcgee69/4f6ddd6b1b971411236f56f36057067b to your computer and use it in GitHub Desktop.
Exploring the Reader functor
-- Reader / unReader syntax
newtype Reader e a = Reader { unReader :: e -> a }
Prelude> :t Reader
Reader :: (e -> a) -> Reader e a -- Reader and unReader are ...
Prelude> :t unReader
unReader :: Reader e a -> (e -> a) -- inverse to each other
Prelude> :{
Prelude| instance Functor (Reader e) where
Prelude| fmap f g = Reader (f . unReader g)
Prelude| :}
Prelude> plusone = \x -> x+1
Prelude> plusone 1
2
Prelude> timestwo = \x -> x * 2
Prelude> timestwo 1
2
Prelude> rdplusone = Reader plusone
Prelude> :t rdplusone
rdplusone :: Num a => Reader a a
Prelude> rdcompose = fmap timestwo rdplusone
Prelude> :t rdcompose
rdcompose :: Num b => Reader b b
Prelude> unReader rdplusone 1
2
Prelude> unReader rdcompose 1
4
-- Different syntax
newtype Reader e a = Reader (e -> a)
Prelude> :{
Prelude| instance Functor (Reader e) where
Prelude| fmap f (Reader g) = Reader (f . g) -- this syntax 'silently' "unboxes g"
Prelude| :}
Prelude> rdplusone = Reader plusone
Prelude> :t rdplusone
rdplusone :: Num a => Reader a a
Prelude> rdcompose = fmap timestwo rdplusone
Prelude> :t rdcompose
rdcompose :: Num b => Reader b b
Prelude> Reader plus = rdplusone
Prelude> plus 1
2
Prelude> Reader comp = rdcompose
Prelude> comp 1
4
-- Reader / unReader syntax
newtype Reader e a = Reader { unReader :: e -> a }
:t Reader
:t unReader
:{
instance Functor (Reader e) where
fmap f g = Reader (f . unReader g)
:}
plusone = \x -> x+1
plusone 1
timestwo = \x -> x * 2
timestwo 1
rdplusone = Reader plusone
:t rdplusone
rdcompose = fmap timestwo rdplusone
:t rdcompose
unReader rdplusone 1
unReader rdcompose 1
-- Different syntax
newtype Reader e a = Reader (e -> a)
:{
instance Functor (Reader e) where
fmap f (Reader g) = Reader (f . g)
:}
rdplusone = Reader plusone
:t rdplusone
rdcompose = fmap timestwo rdplusone
:t rdcompose
Reader plus = rdplusone
plus 1
Reader comp = rdcompose
comp 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment