Here's a pretty trivial example in Haskell - computing the factorial function using a mutable variable.
import Control.Monad.ST
import Data.STRef
fact :: Int -> Int
fact n = runST (fact' n)
fact' :: Int -> ST s Int
fact' n = do a <- newSTRef 1
mapM_ (\x -> modifySTRef a (*x)) [1..n]
readSTRef a
Here the function `fact'` uses mutable variables (encoded in the use of `ST` in its type -- `ST` stands for State Thread) but the function `fact` is pure -- the call to `runST` ensures that none of the side effects leak out of `fact'`.
As with most Haskell code, the types are optional - I included them for clarity.
> As with most Haskell code, the types are optional - I included them for clarity.
I'd just like to make it clear to anyone else reading this. The types aren't optional, but because Haskell has type inference, specifying them is optional.
As with most Haskell code, the types are optional - I included them for clarity.