1

I have the following Haskell function:

g :: (a -> a) -> a
g f = x
  where x = f x

Could somebody please explain, what kind of animal is that, why the function is correct and how it works?

I've tried to pass some function to it, e.g. g (\x -> x + x) or g (\xs -> head xs), but GHC returns me not an instance of Num or cannot construct an infinite type, accordingly. Moreover, there is an infinite loop in the first case. I am confused even more about the x, which is f x, - because where do I get x?

I would be very glad for a complete explanation.

Kirill
  • 183
  • 5
  • 4
    It's a long story. Lookup fixed points, or "fixed point combinator". `g` is a tool to generate recursive values (usually, recursive functions). E.g. try `g (\r x -> if x==0 then 1 else x*r (x-1)) 5` to compute the factorial of 5 recursively. It's usually called [`fix`](https://hackage.haskell.org/package/base-4.14.1.0/docs/Data-Function.html#v:fix), and it's available in the libraries. Another example: compare `fix (True:)` with `let list=True:list in list`. – chi Mar 27 '21 at 11:53
  • thank you, @chi! I'll try to google that. I had totally no idea, how to evaluate it at a first glance, as it seems to be the whole complex of currying, partial application, lazy evaluation and recursion. – Kirill Mar 27 '21 at 12:05
  • 1
    I've closed this as a dup, but don't feel bad about it: you had to know it was called `fix` to find anything. – Paul Johnson Mar 27 '21 at 14:02
  • It is easier to grasp when x is a list whose first element is known unconditionally from the start. For example, one can obtain the infinite [Fibonacci sequence](https://en.wikipedia.org/wiki/Fibonacci_number) by defining first `fibIncr (a,b) = (b,a+b)` and then `fibonacci = map fst (fibs (0,1)) where fibs p0 = g (\ps -> p0:(map fibIncr ps))` – jpmarinier Mar 27 '21 at 15:33

0 Answers0