> I'm pretty sure that it is possible to make a function in Haskell which, while it mutates variables, these variables are all local, so you are still able to offer up a purely functional interface to the world outside of that function.
Indeed, it's called the ST monad. The internals aren't that magical, behind the scenes GHC does some state passing like IO but nothing too fancy. The real trick is using -XRankNTypes for the runST function[1] to track "state threads" at the type-level.
example1 :: Int
example1 = runST $ do
x <- newSTRef 0
forM_ [1..1000] $ \j -> do
writeSTRef x j
readSTRef x
[1]: http://research.microsoft.com/en-us/um/people/simonpj/Papers...This is actually very simple and straightforward to do using the ST monad[0]. See the paper Lazy Functional State Threads[1] for details.
[0] http://hackage.haskell.org/package/base-4.7.0.0/docs/Control...
[1] http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.144...
Re:A Year of Functional Programming
by seanmcdirmid on Monday June 09, 2014 @01:07PM
(#7869291)
State can be local, but you need an escape analysis to verify that it doesn't leak the context if your language supports aliases, which I believe Haskell doesn't (or to say, aliases don't make sense in Haskell).
Whether this is simple and straightforward or even demands some "magic" which isn't usually part of the language semantics - that I don't know. Imperative code seems very doable and maybe even pleasant in Haskell, but I don't know how simple it is to actually write imperative code that is efficient - e.g. destructive updates and all that, rather than making a new value for each "update" and programming in an imperative style though you are really just using immutable values all the time.