# Haskell/Fix and recursion

* Fix and recursion (Solutions)
* Wider Theory
* Denotational semantics
* Equational reasoning
* Program derivation
* Category theory
* The Curry–Howard isomorphism
* fix and recursion
At first glance, the fix function may appear odd and useless . However, there is a theoretical reason for its existence: introducing it into the (typed) lambda calculus as a primitive allows you to define recursive functions.

## Introducing fix

fix is simply defined as:
Doesn't that seem ... magical? You might be wondering: surely fix f will cause an infinite series of nested applications of fs: x = f x = f (f x) = f (f (f ( ... )))? The resolution here is lazy evaluation. Essentially, this infinite sequence of applications of f will be avoided if (and only if) f is a lazy function. Let's see some examples:
Example: fix examples
We first import the Control.Monad.Fix module to bring fix (which is also exported by the Data.Function module) into scope. Then we try three examples. Let us try to see what actually happens in the first example:
The first example uses (+) which is an eager function; it needs the value of x before it can compute ... the value of x. Therefore this calculation will never stop. Let us now look at the second example:
This is quite different: we note that after a single expansion of fix, the evaluation quickly terminates, because const ignores its second argument. The evaluation for the last example is a little different, but we can proceed similarly:
Here 1 : x is already in weak head normal form ((:) is a lazy data constructor), so the expansion stops. This actually creates a cyclic structure. Each time new element of this list is requested by a consumer function, x's definition is consulted, and it is already known to be 1 : x.
Thus, requesting elements from this list one by one will return 1s one after another while requested, without limit. So take 10 (fix (1:)) will produce a list of ten 1s, but trying to print them all by typing fix (1:) into GHCi causes the infinite stream of 1s to be printed.
Well actually it causes the evaluation of show (fix (1:)) = "[" ++ intercalate "," (map show (fix (1:))) ++ "]", and although the map show (fix (1:)) will never complete its work in full, it does produce its output incrementally, piece by piece, one "1" at a time:
This is lazy evaluation at work: the printing function doesn't need to consume its entire input string before beginning to print, it starts printing as soon as it can.
Lastly, iteratively calculating an approximation of a square root of a number,
* Exercises
* What, if anything, will the following expressions converge to?
* fix ("hello"++)
* fix (\x -> cycle (1:x))
* fix reverse
* fix id
* fix (\x -> take 2 $ cycle (1:x))

## fix and fixed points

fix can also be defined in a way that does not introduce structural sharing:
A fixed point of a function f is a value a such that f a == a. For example, 0 is a fixed point of the function (* 3) since 0 * 3 == 0. This is where the name of fix comes from: it finds the least-defined fixed point of a function. (We'll come to what "least defined" means in a minute.) For the two aforementioned examples that converge, this is readily seen:
And since there's no number x such that 2+x == x, it also makes sense that fix (2+) diverges.
* Exercises
* For each of the functions f in the above exercises for which you decided that fix f converges, verify that fix f finds a fixed point.
In fact, it's obvious from the definition of fix that it finds a fixed point. All we need to do is write the equation for fix the other way around:
Which is precisely the definition of a fixed point! So it seems that fix should always find a fixed point. But sometimes fix seems to fail at this, as sometimes it diverges. We can repair this property, however, if we bring in some denotational semantics. Every Haskell type actually includes a special value called bottom, written ⊥. So the values with type, for example, Int include, in fact, ⊥ as well as 1, 2, 3 etc.. Divergent computations are denoted by a value of ⊥, i.e., we have that fix (2+) = ⊥.
The special value undefined is also denoted by this ⊥. Now we can understand how fix finds fixed points of functions like (2+):
Example: Fixed points of (2+)
So feeding undefined (i.e., ⊥) to (2+) gives us undefined back. So ⊥ is a fixed point of (2+)!
In the case of (2+), it is the only fixed point. However, there are other functions f with several fixed points for which fix f still diverges: fix (*3) diverges, but we remarked above that 0 is a fixed point of that function. This is where the "least-defined" clause comes in. Types in Haskell have a partial order on them called definedness. In any type, ⊥ is the least-defined value (hence the name "bottom"). For simple types like Int, the only pairs in the partial order are ⊥ ≤ 1, ⊥ ≤ 2 and so on. We do not have m ≤ n for any non-bottom Ints m, n. Similar comments apply to other simple types like Bool and. For "layered" values such as lists or Maybe, the picture is more complicated, and we refer to the chapter on denotational semantics.
So since ⊥ is the least-defined value for all types and fix finds the least-defined fixed point, if f ⊥ = ⊥, we will have fix f = ⊥ (and the converse is also true). If you've read the denotational semantics article, you will recognise this as the criterion for a strict function: fix f diverges if and only if f is strict.

## Recursion

If you have already come across examples of fix, chances are they were examples involving fix and recursion. Here's a classic example:
Example: Encoding recursion with fix
Here we have used fix to "encode" the factorial function: note that (if we regard fix as a language primitive) our second definition of fact doesn't involve recursion at all. In a language like the typed lambda calculus that doesn't feature recursion, we can introduce fix in to write recursive functions in this way. Here are some more examples:
Example: More fix examples
So how does this work? Let's first approach it from a denotational point of view with our fact function. For brevity let's define:
This is the same function as in the first example above, except that we gave a name to the anonymous function so that we're computing fix fact' 5 now. fix will find a fixed point of fact', i.e. the function f such that f == fact' f. But let's expand what this means:
All we did was substitute f for rec in the definition of fact'. But this looks exactly like a recursive definition of a factorial function! fix fact' feeds itself to fact' as its first parameter thus creating a recursive function out of a higher-order function (a.k.a. a functional, in old time LISP parlance) which expresses one step of the overall recursive calculation.
We can also consider things from a more operational point of view. Let's actually expand the definition of fix fact':
Notice that the use of fix allows us to keep "unraveling" the definition of fact': every time we hit the else clause, we produce another copy of fact' via the evaluation rule fix fact' = fact' (fix fact'), which functions as the next call in the recursion chain. Eventually we hit the then clause and bottom out of this chain.
And with the sharing definition of fix as at the top of this page, fix fact' would create an actually recursive function, which uses its own actual self to make the recursive call, instead of its copy:
This is made possible by the fact that Haskell's let allows recursive definitions, and is actually like Scheme's letrec in this regard. The non-sharing fix definition does not use this and would work with non-recursive let as well -- although it itself is also defined recursively (here), the function it creates is not actually self-referential and achieves recursion by recreating its own copy and calling it instead, as we've seen above. That's why one way to add recursion to a non-recursive language is to add fix to it, as a primitive construct.
Non-recursive definitions for fix also exist. The simplest and most famous of them is known as Y combinator. In non-typed Haskell it could've been written as y = u . (. u) where u x = x x is known as U combinator.
* Exercises
* Expand the other two examples we gave above in this sense. You may need a lot of paper for the Fibonacci example!
* Write non-recursive versions of filter and foldr.

## The typed lambda calculus

In this section we'll expand upon a point mentioned a few times in the previous section: how fix allows us to encode recursion in the typed lambda calculus. It presumes you've already met the typed lambda calculus. Recall that in the lambda calculus, there is no let clause or top-level bindings. Every program is a simple tree of lambda abstractions, applications and literals. Let's say we want to write a fact function. Assuming we have a type called Nat for the natural numbers, we'd start out something like the following:
The problem is, how do we fill in the <blank>? We don't have a name for our function, so we can't call it recursively. The only way to bind names to terms is to use a lambda abstraction, so let's give that a go:
This expands to:
We still have a <blank>. We could try to add one more layer in:
It's pretty clear we're never going to be able to get rid of this <blank>, no matter how many levels of naming we add in. Never, that is, unless we use fix, which, in essence, provides an object from which we can always unravel one more layer of recursion and still have what we started off:
This is a perfect factorial function in the typed lambda calculus plus fix.
fix is actually slightly more interesting than that in the context of the typed lambda calculus: if we introduce it into the language, then every type becomes inhabited, because given some concrete type T, the following expression has type T:
This, in Haskell-speak, is fix id, which is denotationally ⊥. So we see that as soon as we introduce fix to the typed lambda calculus, the property that every well-typed term reduces to a value is lost.

## Fix as a data type

It is also possible to make a fix data type in Haskell.
There are three ways of defining it.
or using the RankNTypes extension
Mu and Nu help generalize folds, unfolds and refolds.
Mu and Nu are restricted versions of Fix. Mu is used for making inductive noninfinite data and Nu is used for making coinductive infinite data. Eg)
Unlike the fix point function the fix point types do not lead to bottom. In the following code Bot is perfectly defined. It is equivalent to the unit type.
The Fix data type cannot model all forms of recursion. Take for instance this nonregular data type.
It is not easy to implement this using Fix.
* Fix and recursion
* Solutions to exercises
* Wider Theory
* Denotational semantics
* >> Equational reasoning
* >> Program derivation
* >> Category theory
* >> The Curry–Howard isomorphism
* >> fix and recursion
* Haskell
* Haskell Basics
* >> Elementary Haskell
* >> Intermediate Haskell
* >> Monads
* Advanced Haskell
* >> Fun with Types
* >> Wider Theory
* >> Haskell Performance
* Libraries Reference
* >> General Practices
* >> Specialised Tasks