Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed point combinator in Haskell

The fixed point combinator doesn't always produce the right answer given the definition:

fix f = f (fix f)

The following code does not terminate:

fix (\x->x*x) 0

Of course, fix can't always produce the right answer, but I was wondering, can this be improved?

Certainly for the above example, one can implement some fix that looks like

fix f x | f x == f (f x)  = f x
        | otherwise       = fix f (f x)

and gives the correct output.

What is the reason the above definition (or something even better, as this one only handle function with 1 parameter) is not used instead?

like image 362
Chao Xu Avatar asked Nov 11 '11 20:11

Chao Xu


People also ask

What is fix Haskell?

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: f = fact' f = \n -> if n == 0 then 1 else n * f (n-1)

What is a Combinator Lambda?

A combinator is a closed lambda expression, meaning that it has no free variables.

What is Z Combinator?

Julia Language Combinators The Y or Z Combinator This combinator takes a function and returns a function that when called with argument x , gets passed itself and x .


1 Answers

Fixed point combinator finds the least-defined fixed point of a function, which is ⊥ in your case (non-termination indeed is undefined value).

You can check, that in your case

(\x -> x * x) ⊥ = ⊥

i.e. really is fixed point of \x -> x * x.

As for why is fix defined that way: the main point of fix is to allow you use anonymous recursion and for that you do not need more sophisticated definition.

like image 191
Vitus Avatar answered Sep 19 '22 14:09

Vitus