[Haskell-cafe] REALLY simple STRef examples

Bryan Burgers bryan.burgers at gmail.com
Fri Jul 21 20:40:58 EDT 2006


On 7/21/06, S C Kuo <sck04u at cs.nott.ac.uk> wrote:
> 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

Forgive me for not understanding, but I was hoping you would explain a
choice you made in your code. Why did you define foreach and then use

> foreach [1..n] (\x -> modifySTRef r (*x))

Instead of simply using

> mapM_ (\x -> modifySTRef r (*x)) [1..n]

? I tried it out in GHCi, and it worked fine, and I have seen code
that has been defined as a flip to take advantage of partial
application. But your code doesn't seem to take advantage of partial
application, so why did you define 'foreach' and then use it instead
of using 'mapM_'? I am just curious, and have always been interested
in reasons behind coding style.

Bryan Burgers


More information about the Haskell-Cafe mailing list