Created
October 6, 2019 00:52
-
-
Save Willmo36/e8793b172e775216892e978985c7257b to your computer and use it in GitHub Desktop.
Max learning various comonads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
import Control.Comonad | |
data Stream a = a :> Stream a | |
instance Functor Stream where | |
fmap f (a :> rest) = f a :> (fmap f rest) | |
instance Comonad Stream where | |
extract (a :> _)= a | |
duplicate w@(_ :> rest) = w :> duplicate rest | |
data Store s a = Store (s -> a) s | |
instance Functor (Store s) where | |
fmap g (Store f s) = Store (g . f) s | |
instance Comonad (Store s) where | |
extract (Store f s) = f s | |
duplicate (Store f s) = Store (\s' -> (Store f s')) s | |
experiment :: Functor f => (s -> f s) -> Store s a -> f a | |
experiment g (Store f s) = f <$> g s | |
maxstore :: Store String Int | |
maxstore = Store length "hello" | |
data Env e a = Env e a | |
instance Functor (Env e) where | |
fmap f (Env e a) = Env e (f a) | |
instance Comonad (Env e) where | |
extract (Env e a) = a | |
duplicate w@(Env e a) = Env e w | |
ask :: (Env e a) -> e | |
ask (Env e a) = e | |
asks :: (e -> e') -> (Env e a) -> e' | |
asks f (Env e a) = f e | |
env :: e -> a -> Env e a | |
env = Env | |
data Settings = Settings {padAmount :: Int, padChar :: Char } | |
mySettings = Settings {padAmount = 6, padChar = '-'} | |
pad :: Env Settings String -> String | |
pad w = let pa = asks padAmount w | |
pc = asks padChar w | |
str = extract w | |
in ((replicate pa pc) :: String) ++ str | |
main :: IO () | |
-- main = putStrLn $ show $ extract maxstore | |
main = putStrLn $ show $ pad (env mySettings "max") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment