haskell - State Monad ExampleProblem -
haskell - State Monad ExampleProblem -
i working on problem , had asked related question. implementation of state monad farther refine code tried implement using 1 increment function.
module stateexample import control.monad.state info globstate = globstate { c1 :: int, c2:: int, c3:: int} deriving (show) newglobstate:: globstate newglobstate = globstate { c1=0,c2=0,c3=0 } incr :: string-> state globstate () incr x = modify(\g -> g {x =x g + 1}) main:: io() main = allow a1= flip execstate newglobstate $ incr c1 incr c2 incr c1 print
but here getting error
`x' not (visible) constructor field name
how can remove error?
you have nail weakness in haskell: records not first class values! indeed, nice write have done, not possible. however, can utilize different libraries accomplish desired effect. how looks if utilize fclabels:
{-# language templatehaskell, typeoperators #-} module stateexample import control.monad.state hiding (modify) import data.label (mklabels) import data.label.pure ((:->)) import data.label.purem info globstate = globstate { _c1 :: int , _c2 :: int , _c3 :: int } deriving show $(mklabels [''globstate]) newglobstate:: globstate newglobstate = globstate { _c1 = 0, _c2 = 0, _c3 = 0 } incr :: (globstate :-> int) -> state globstate () incr x = modify x (+1) main :: io () main = allow = flip execstate newglobstate $ incr c1 incr c2 incr c1 print
there magic parts here. define globstate
same record names prependend underscore. function mklabels
uses templatehaskell
define "lenses" every field in record. these lenses have same name without underscore. argument (globstate :-> int)
incr
such lens, , can utilize modify
function data.label.purem
updates records defined way within state monad. hide modify
control.monad.state
, avoid collision.
you can @ other functions in documentation purem other functions usable state monads, gets
, puts
.
if not have fclabels
installed, have cabal
executable cabal-install
bundle (which if install haskell platform), can install fclabels
running:
cabal install fclabels
if first time run cabal
, first need update database:
cabal update
haskell
Comments
Post a Comment