[Haskell-cafe] REALLY simple STRef examples
S C Kuo
sck04u at cs.nott.ac.uk
Fri Jul 21 13:12:51 EDT 2006
Not totally relevant to what the discussion has evolved to, but I wrote
a factorial function using STRefs (in the spirit of the Evolution of a
Haskell programmer) and I think it qualifies as a really simple example.
Code follows:
import Data.STRef
import Control.Monad.ST
foreach :: (Monad m) => [a] -> (a -> m b) -> m ()
foreach = flip mapM_
-- Bryn Keller's foreach, but with type restrictions
fac :: (Num a, Enum a) => a -> a
fac n = runST (fac' n)
fac' :: (Num a, Enum a) => a -> ST s a
fac' n = do r <- newSTRef 1
foreach [1..n] (\x -> modifySTRef r (*x))
x <- readSTRef r
return x
Chad Scherrer wrote:
> The IO monad hasn't given me too much trouble, but I want to be sure
> to structure things the way "they should be". If I get everything
> running using IO first and then have type-checking problems with ST,
> it will be tempting to just slap on an unsafePerformIO and call it
> good. Sure, it's really doing the same thing anyway, but it just comes
> out looking like a hack.
>
> On 7/20/06, Bulat Ziganshin <bulat.ziganshin at gmail.com> wrote:
>> Hello Chad,
>>
>> Friday, July 21, 2006, 12:26:58 AM, you wrote:
>>
>> > Ok, I see now why the return is necessary.
>>
>> btw, it may be helpful to read "IO inside" material. ST monad is not
>> very different from IO monad - it only limited to operations on STRef
>> and STArray, so that it can't have side-effects visible outside of
>> runST statement used to run ST computation
>>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list