順便求C4F指點下點樣係Haskell度implement Y/fix combinator?
i.e.呢舊嘢:
Y = λ y . ( λ x . y (x x)) ( λ x . y (x x))
or
Y = λ f . ( λ x . f (x x)) ( λ x . f (x x))
or
Yf
Yf produces fYf produces f(fYf) produces f(f(fYf)) ... as recursion
我見stackoverflow話Y唔屬於Haskell built-in 嘅任何一個type, 就咁define Y 去 implement會出error, 咁應該點做呢? 可否用factorial做example教下點implement Y combinator?
Thanks in advance!
according to what I am aware of, it is not possible. But I think Y combinator is implemented internally in haskell?
係呀, Haskell個built-in Y combinator叫fixed-point combinator(i.e. fix), import個Data.Function 或者 Control.Monad.Fix就用得, 唔駛自己嚟, 不過自己當然都嚟唔到, define唔到個又pure又true嘅Y combinator, 最多打下茅波, 整個超殘廢版 :
let fixedPoint fun = let {x = fun x} in x
or simply
let y f = f (y f)
No. They are the same thing only expressed differently. It is not possible to express the fixed-point combinator using lambda calculus in Haskell "fix" is the same thing. The only difference is that:
y f = f (y f)
is not a normal definition in the mathematical sense. It is a equation. Essentially we want to solve this equation:
x = f x
We want to find a value x such that f x equals to x itself. Hence it is called a fixed point. The thing with an equation is that it may not be solvable or has multiple or infinite solution. In Haskell, if you write
y f = f (y f)
you get
f (f (f (f (f .......))
so y is indeed the fixed point combinator. However, you can only do it in a language with lazy evaluation. You can do the same in scheme of lisp but you will get a stack overflow if you write something like:
(define fix (lambda (f) (f (y f))))
(define fact-0
(lambda (next)
(lambda (n) (if (= 0 n) 1 (* n (next (- n 1)))))))
;; stack overflow
(fix fact-0)
哈哈, 你啱, 既然用Haskell都implement唔都個純Y combinator (i.e. Y = λ y . ( λ x . y (x x)) ( λ x . y (x x))), 咁Haskell個fix (imported from Data.Function or Control.Monad.Fix)又點可能係個純Y combinator呢? 直頭係自相矛盾啦!
If g(x) = f(x) for all x, then are g and f the same thing?
我諗你expect我會答not the same thing, 咁咪唔係自相矛盾囉, 但你可能誤會咗我嘅意思, 我只係想講Haskell不能implement a pure Y combinator , as you said咋!