[Haskell-cafe] Reader monad wrapping State monad
michael rice
nowgate at yahoo.com
Thu Feb 3 20:18:43 CET 2011
Given the first program, it seems that the unchanging first element of the tuple could be handled by a Reader monad, leading to the second program, where b becomes the state, but how do I get the constant a from the Reader monad?
Michael
==================
import Control.Monad.State
type GeneratorState = State (Double,Double)
sqrtST :: GeneratorState Double
sqrtST = do (a,b0) <- get
let b1 = (b0**2.0+a)/(2.0*b0)
(if (abs (a-b1**2.0)) < 0.000001
then
return b1
else do
put (a,b1)
sqrtST)
mySqrt a = let b = a/2.0
in fst ( runState sqrtST (a,b) )
{-
*Main> mySqrt 2.0
1.4142135623746899
-}
==================
import Control.Monad.Reader
import Control.Monad.State
type GeneratorState = State Double
sqrtST :: GeneratorState Double
sqrtST = do b0 <- get
let a = ?
b1 = (b0**2.0+a)/(2.0*b0)
(if (abs (a-b1**2.0)) < 0.000001
then
return b1
else do
put b1
sqrtST)
mySqrt a = let b = a/2.0
in runReaderT (runState sqrtST b) a
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20110203/19e25b50/attachment-0001.htm>
More information about the Haskell-Cafe
mailing list