3 ms·
"Functional" doesn't necessarily imply "pure", but some functional languages do offer great tools for reasoning about purity and state. Here is a simple example
by caconym_ 10y ago
"Functional" doesn't necessarily imply "pure", but some functional languages do offer great tools for reasoning about purity and state. Here is a simple example in Haskell:
showTenRandoms :: IO ()
showTenRandoms = do
gen <- getStdGen
let randoms = unfoldr (Just . next) gen
putStrLn $ show $ take 10 randoms
We create the random number generator "in the `IO` monad", where non-pure actions are allowed. Then we pass it to `unfoldr`, which is a pure function (you can tell because it's in a `let` binding), to generate an infinite list of random integers. This works because when we use the generator to get a random number, it isn't mutated, but instead returns a random number and a new generator. The `unfoldr` call basically just iterates on that operation.
If you don't know Haskell, this code will probably look like nonsense, so you'll just have to take my word for it. I'd be happy to explain or clarify further.