Y Combinator in Haskell

半腔热情 提交于 2019-11-28 03:23:19

Here's a non-recursive definition of the y-combinator in haskell:

newtype Mu a = Mu (Mu a -> a)
y f = (\h -> h $ Mu h) (\x -> f . (\(Mu g) -> g) x $ x)

hat tip

The Y combinator can't be typed using Hindley-Milner types, the polymorphic lambda calculus on which Haskell's type system is based. You can prove this by appeal to the rules of the type system.

I don't know if it's possible to type the Y combinator by giving it a higher-rank type. It would surprise me, but I don't have a proof that it's not possible. (The key would be to identify a suitably polymorphic type for the lambda-bound x.)

If you want a fixed-point operator in Haskell, you can define one very easily because in Haskell, let-binding has fixed-point semantics:

fix :: (a -> a) -> a
fix f = f (fix f)

You can use this in the usual way to define functions and even some finite or infinite data structures.

It is also possible to use functions on recursive types to implement fixed points.

If you're interested in programming with fixed points, you want to read Bruce McAdam's technical report That About Wraps it Up.

Joey Adams

The canonical definition of the Y combinator is as follows:

y = \f -> (\x -> f (x x)) (\x -> f (x x))

But it doesn't type check in Haskell because of the x x, since it would require an infinite type:

x :: a -> b -- x is a function
x :: a      -- x is applied to x
--------------------------------
a = a -> b  -- infinite type

If the type system were to allow such recursive types, it would make type checking undecidable (prone to infinite loops).

But the Y combinator will work if you force it to typecheck, e.g. by using unsafeCoerce :: a -> b:

import Unsafe.Coerce

y :: (a -> a) -> a
y = \f -> (\x -> f (unsafeCoerce x x)) (\x -> f (unsafeCoerce x x))

main = putStrLn $ y ("circular reasoning works because " ++)

This is unsafe (obviously). rampion's answer demonstrates a safer way to write a fixpoint combinator in Haskell without using recursion.

Theo Belaire

Oh

this wiki page and This Stack Overflow answer seem to answer my question.
I will write up more of an explanation later.

Now, I've found something interesting about that Mu type. Consider S = Mu Bool.

data S = S (S -> Bool)

If one treats S as a set and that equals sign as isomorphism, then the equation becomes

S ⇋ S -> Bool ⇋ Powerset(S)

So S is the set of sets that are isomorphic to their powerset! But we know from Cantor's diagonal argument that the cardinality of Powerset(S) is always strictly greater than the cardinality of S, so they are never isomorphic. I think this is why you can now define a fixed point operator, even though you can't without one.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!