by tromp · 2y ago · 0 comments
It's interesting to compare Elixir to that other immutable programming language: Haskell.
In Elixir, a binding
counter = counter + 1
binds counter to the old value of counter, plus 1.
In Haskell it instead binds counter to the new value plus 1.Of course that doesn't make sense, and indeed this causes an infinite loop when Haskell tries to evaluate counter.
BUT it does make sense for certain recursive data structures, like an infinite list of 1s:
ones = 1 : ones
We can check this by taking some finite prefix: ghci> take 5 ones
[1,1,1,1,1]
Another example is making a list of all primes, where you don't need to decide in advance how many elements to limit yourself to.Can you define such lazy infinite data structures in Elixir?
Stream.iterate(1, fn(x) -> x end)
|> Enum.take(5)
[1, 1, 1, 1, 1] ghci> fibs = 0 : 1 : zipWith (+) fibs (drop 1 fibs)
ghci> take 10 fibs
[0,1,1,2,3,5,8,13,21,34]
? Stream.unfold({0,1}, fn {a,b} -> {a,{b,a+b}} end)
|> Enum.take(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
https://rosettacode.org/wiki/Fibonacci_sequence#Elixir int i = 0;
while (i < 5) {
i = i+1;
printf("i: %d\n", i);
}
whereas in Haskell I could hypothetically something like let i = 0 in
whileM (pure (i < 5)) $
let i = i + 1 in
printf "i: %d\n" i
but the inner assignment would not have any effect on the variable referenced by the condition in the while loop – it would only affect what's inside the block it opens.(And as GP points out, i=i+1 is an infinite loop in Haskell. But even if it was used to build a lazy structure, it would just keep running the same iteration over and over because when the block is entered, i still has the value that was set outside.)
checkIORef r p = fmap p (readIORef r)
usingIORef r a = readIORef r >>= a
the example can be written as main = do
i <- newIORef (0 :: Int)
whileM_ (checkIORef i (< 5)) $ do
modifyIORef i (+1)
usingIORef i (printf "i: %d\n")
That said, even if one actually needs to mix mutable variables with I/O actions like printing, I'm not sure I would recommend using IORefs for it. But opening the can of MonadIO m => StateT Int m () is for another day.Although I don’t think it’ll be quite as elegant as the Haskell code.