YCombinator在Swift中不起作用 [英] YCombinator not working in Swift
问题描述
我正在尝试创建一个lambda函数,以获取阶乘函数,但这会引发分段错误和错误.我如何在Swift中使用它.请观看此视频,以获取我想做的事情的参考
I am trying to create a lambda function as such to get a factorial function but this throws a segmentation fault and errors out. How do I get this working in Swift. Please look at this video for reference on what I am trying to do http://www.confreaks.com/videos/1287-rubyconf2012-y-not-adventures-in-functional-programming
typealias f = () -> ()
typealias g = (Int) -> (Int)
typealias F = Any -> g
let y = { (gen: Any) -> g in
(gen as F)(gen)
}
let fact = y({ (gen: Any) -> g in
{ (n: Int) -> Int in
if n == 0 {
return 1
} else {
return n * (gen as F)(gen)(n - 1)
}
}
})
fact(10)
推荐答案
您可以使用递归类型实现真正的(没有显式递归)Y组合器,而无需任何不安全的技巧(贷记
You can implement a real (without explicit recursion) Y combinator using a recursive type, without any unsafe tricks (credits to Rosetta Code):
struct RecursiveFunc<F> {
let o : RecursiveFunc<F> -> F
}
func Y<A, B>(f: (A -> B) -> A -> B) -> A -> B {
let r = RecursiveFunc<A -> B> { w in f { w.o(w)($0) } }
return r.o(r)
}
let factorial = Y { (f: Int -> Int) -> Int -> Int in
{ $0 <= 1 ? 1 : $0 * f($0-1) }
}
println(factorial(10))
Any
doesn't really help because Any
cannot represent function types.
更新:从Xcode 6.1 beta 3开始,Any
可以表示函数类型,并且您的代码可以编译并正常工作.
Update: Starting in Xcode 6.1 beta 3, Any
can represent function types, and your code compiles and works correctly.
这篇关于YCombinator在Swift中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!