Haskell: State Monad -
i'm trying learn haskell. wrote code uses global state , can change using 2 functions (i.e. change1 , change 2). also, have included lens can learn too. problem last line of code. don't understand why cannot include 2 last lines in main. it'd run if remove either of them.
{-# language templatehaskell #-} module dd (main, ma, change1,change2, dp(dp)) import control.lens import control.monad.state import control.monad.io.class (liftio) data dp = dp {_sr :: int , _fl :: int} deriving (show) makelenses ''dp plus :: dp -> dp plus = on (sr) (+90) mult4 :: dp -> dp mult4 = on (fl) (*100) change1 :: state dp () change1 = modify plus change2 :: state dp () change2 = modify mult4 ma :: state dp () ma = change1 change2 main = runstate ma (dp 2 3) evalstate ma (dp 2 3)-- here problem
edit: i'm bit confused: why below code runs without error?
data dp = dp {_sr :: int , _fl :: int} deriving (show) makelenses ''dp gs :: statet dp io int gs = d <- gets _sr liftio $ print (d) dd<- uses sr (10<=) if (dd) return (10) else return (90) main = runstatet gs (dp 3 6) evalstatet gs (dp 3 6)
in case do-notation
syntactic sugar for
(runstate ma (dp 2 3)) >> (evalstate ma (dp 2 3))
the type of (>>)
monad m => m -> m b -> m b
means runstate ma (dp 2 3)
, evalstate ma (dp 2 3)
must in same monad, not
but code doesn't work reason. function main
has following type annotation: main :: io a
means main
expects action performed in (for example printing results)
main :: io () main = print $ runstate ma (dp 2 3) print $ evalstate ma (dp 2 3)
that works, because
- type of
print $ runstate ma (dp 2 3)
io ((), dp)
- type of
print $ evalstate ma (dp 2 3)
io ()
hence, inferred type >>
io ((), dp) -> io () -> io ()
doesn't violate monad m => m -> m b -> m b
. , resulting type io ()
suits main :: io a
Comments
Post a Comment