这是 Scala 中 Y-combinator 的实现:
scala> def Y[T](func: (T => T) => (T => T)): (T => T) = func(Y(func))(_:T)
Y: [T](func: (T => T) => (T => T))T => T
scala> def fact = Y {
| f: (Int => Int) =>
| n: Int =>
| if(n <= 0) 1
| else n * f(n - 1)}
fact: Int => Int
scala> println(fact(5))
120
Q1:结果如何120
一步步得出?因为Y(func)
定义为func(Y(func))
,所以Y应该越来越大,Y在哪里丢失120
了,在执行过程中又是如何出来的?
Q2:两者有什么区别
def Y[T](func: (T => T) => (T => T)): (T => T) = func(Y(func))(_:T)
和
def Y[T](func: (T => T) => (T => T)): (T => T) = func(Y(func))
它们在scala REPL中是相同的类型,但是第二个不能打印结果120
?
scala> def Y[T](func: (T => T) => (T => T)): (T => T) = func(Y(func))
Y: [T](func: (T => T) => (T => T))T => T
scala> def fact = Y {
| f: (Int => Int) =>
| n: Int =>
| if(n <= 0) 1
| else n * f(n - 1)}
fact: Int => Int
scala> println(fact(5))
java.lang.StackOverflowError
at .Y(<console>:11)
at .Y(<console>:11)
at .Y(<console>:11)
at .Y(<console>:11)
at .Y(<console>:11)