by consilient · 3y ago · 0 comments
Haskell allows this, you just have to actually demonstrate that the mutation is local:
statefulSum :: [Int] -> Int
statefulSum xs = runST $ do
n <- newSTRef 0
traverse (\x -> modifySTRef n (\y -> y + x)) xs
readSTRef nBut Odersky's point is that (at least in Scala) it is even simpler (and thus should be preferred) to do it with raw (but still local!) mutation.
I'm afraid we don't have anything like ST in any Scala library that I know of :(