4 ms·
> imperative code with some local mutability Haskell allows this, you just have to actually demonstrate that the mutation is local: statefulSum :: [Int] -
by consilient 4y ago
> imperative code with some local mutability
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 n
- sideeffffect 4y agoAnd you can do it with a state monad in Scala too. But 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. https://www.youtube.com/watch?v=QRcD9Zc7eq4&t=943s https://www.youtube.com/watch?v=QRcD9Zc7eq4&t=943s
- consilient 4y ago`ST` isn't `State` (though the interface is very similar), it's a restricted variant of `IO`. An `STRef` is an actual mutable reference, backed by actual memory.
- sideeffffect 4y agoOh, I see. Nice! I'm afraid we don't have anything like ST in any Scala library that I know of :(