順便求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!
純lambda calculus係唔type嘅。Haskell有type system限制(Hindley Milner type system唔能夠代表到y combinator嘅type),唔可以寫到純lambda calculus嘅y combinator。
http://stackoverflow.com/questions/4273413/y-combinator-in-haskell
Haskell嘅fixed point operator叫fix
GHCi, version 7.6.3:
http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> import Data.Function
Prelude Data.Function> :t fix
fix :: (a -> a) -> a
Prelude Data.Function> let fact f n = if n == 0 then 1 else n * f (n - 1)
Prelude Data.Function> :t fix fact
fix fact :: (Eq a, Num a) => a -> a
Prelude Data.Function> fix fact 5
120
Prelude Data.Function> map (fix fact) [0..10]
[1,1,2,6,24,120,720,5040,40320,362880,3628800]
Prelude Data.Function> let y f = f (y f) -- not really the y combinator
Prelude Data.Function> :type y
y :: (t -> t) -> t
Prelude Data.Function> y fact 5
120
Prelude Data.Function> map (y fact) [0..10]
[1,1,2,6,24,120,720,5040,40320,362880,3628800]
Prelude Data.Function>
我以前響高登講過點用lisp寫y combinator。不過因為strict evaluation關係,同pure lambda calculus都係有dd分別。
http://forum14.hkgolden.com/view.aspx?type=SW&message=5112005&highlight_id=0&page=2&authorOnly=False