Skip to content

Commit

Permalink
Monad instance for State''
Browse files Browse the repository at this point in the history
  • Loading branch information
Anastasios Valtinos committed Nov 1, 2022
1 parent 7d2eee0 commit 165941f
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{-# LANGUAGE FlexibleContexts #-}
module MonadicCode where

import Control.Monad.State as CMS


-- implement `ap` yourself

ap'' :: Monad m => m (a -> b) -> m a -> m b
ap'' mf mx = do
f <- mf
x <- mx
return (f x)


-- Another exercise. Write fmap with ap & pure

-- fmap'' :: Functor f => (a -> b) -> f a -> f b
fmap'' f a = pure f `ap` a

-- Ex 3.3 Write ZipList functor instancce

newtype ZipList a = ZipList { getZipList :: [a] } deriving (Eq, Show)
-- so getZipList type :: ZipList a -> [a]

instance Functor ZipList where
fmap f (ZipList gz) = ZipList $ fmap f gz

newtype State'' s a = State { runState :: s -> (a,s) }

-- runState :: State s a -> s -> (a,s)

instance Functor (State'' s) where
fmap f (State rs) = State $ \s -> let (a,s') = rs s in (f a, s')

instance Applicative (State'' s) where
-- pure :: x -> State s x
pure x = State $ \n -> (x, n)
State fz <*> State xz = State $ \s -> let a = fst $ xz s
ab = fst $ fz s
in (ab a, s)
28 changes: 27 additions & 1 deletion Haskell Excercises & Code/Alejandro - Book of Monads/monadic.hs
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,30 @@ newtype ZipList a = ZipList { getZipList :: [a] } deriving (Eq, Show)
-- so getZipList type :: ZipList a -> [a]

instance Functor ZipList where
fmap f (ZipList gz) = ZipList $ fmap f gz
fmap f (ZipList gz) = ZipList $ fmap f gz

newtype State'' s a = State { runState' :: s -> (a,s) }

-- runState :: State s a -> s -> (a,s)

instance Functor (State'' s) where
fmap f (State rs) = State $ \s -> let (a,s') = rs s in (f a, s')

instance Applicative (State'' s) where
-- pure :: x -> State s x
pure x = State $ \n -> (x, n)
State fz <*> State xz = State $ \s -> let a = fst $ xz s
ab = fst $ fz s
in (ab a, s)

instance Monad (State'' s) where
return x = State $ \s -> (x, s)
rsa >>= f = State $ \input -> let (a, input') = runState' rsa input
(a', input'') = runState' (f a) input'
in (a', input'')



-- let (a, s) = rsa input in (f a, s)
-- m a -> (a -> m b) -> m b
-- State s a -> ( a -> State s b) -> State s b

0 comments on commit 165941f

Please sign in to comment.