I'm starting to wrap my head around Haskell and do some exciting experiments. And there's one thing I just seem to be unable to comprehend (previous "imperativist" experience talks maybe). Recently, I was yearning to implement integer division function as if there where no multiply/divide operations. An immensely interesting brain-teaser which led to great confusion.
divide x y =
if x < y then 0
else 1 + divide (x - y) y
I compiled it and it.. works(!). That's mind-blowing. However, I was told, I was sure that variables are immutable in Haskell. How comes that with each recursive step variable x keeps it's value from previous step? Or is my glorious compiler lying to me? Why does it work at all?
x - yyou pass to the recursive call does not affect the value ofxin the caller.x. This has nothing to do with mutability, like it has nothing to do with mutability if you define two functionsf x = sin xandg x = tanh x.letandwhereand of course you can also define them at the top-level. And of course parameters are just a kind of variable.