I don't claim to understand this at all, but if this helps anyone...then yippee.
Consider the definition of fix
. fix f = let x = f x in x
. The mind-boggling part is that x
is defined as f x
. But think about it for a minute.
x = f x
Since x = f x, then we can substitute the value of x
on the right hand side of that, right? So therefore...
x = f . f $ x -- or x = f (f x)
x = f . f . f $ x -- or x = f (f (f x))
x = f . f . f . f . f . f . f . f . f . f . f $ x -- etc.
So the trick is, in order to terminate, f
has to generate some sort of structure, so that a later f
can pattern match that structure and terminate the recursion, without actually caring about the full "value" of its parameter (?)
Unless, of course, you want to do something like create an infinite list, as luqui illustrated.
TomMD's factorial explanation is good. Fix's type signature is (a -> a) -> a
. The type signature for (\recurse d -> if d > 0 then d * (recurse (d-1)) else 1)
is (b -> b) -> b -> b
, in other words, (b -> b) -> (b -> b)
. So we can say that a = (b -> b)
. That way, fix takes our function, which is a -> a
, or really, (b -> b) -> (b -> b)
, and will return a result of type a
, in other words, b -> b
, in other words, another function!
Wait, I thought it was supposed to return a fixed point...not a function. Well it does, sort of (since functions are data). You can imagine that it gave us the definitive function for finding a factorial. We gave it a function that dind't know how to recurse (hence one of the parameters to it is a function used to recurse), and fix
taught it how to recurse.
Remember how I said that f
has to generate some sort of structure so that a later f
can pattern match and terminate? Well that's not exactly right, I guess. TomMD illustrated how we can expand x
to apply the function and step towards the base case. For his function, he used an if/then, and that is what causes termination. After repeated replacements, the in
part of the whole definition of fix
eventually stops being defined in terms of x
and that is when it is computable and complete.