Skip to content

Instantly share code, notes, and snippets.

@bananu7
Created September 24, 2015 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bananu7/d39f8477fa795d3c3287 to your computer and use it in GitHub Desktop.
Save bananu7/d39f8477fa795d3c3287 to your computer and use it in GitHub Desktop.
ST monad example
import Control.Monad
import Control.Monad.ST
import Data.STRef
imperativeSum :: Num a => [a] -> a
imperativeSum xs = runST $ do
n <- newSTRef 0 -- Create an STRef (place in memory to store values)
forM_ xs $ \x -> do -- For each element of xs ..
modifySTRef n (+x) -- add it to what we have in n.
readSTRef n
main :: IO ()
main = print $ imperativeSum [1..10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment