Created
September 24, 2015 06:46
-
-
Save bananu7/d39f8477fa795d3c3287 to your computer and use it in GitHub Desktop.
ST monad example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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