Skip to content

Instantly share code, notes, and snippets.

@oleganza
Last active August 29, 2015 14:02
Show Gist options
  • Save oleganza/85f32f6ad860c0d53f8c to your computer and use it in GitHub Desktop.
Save oleganza/85f32f6ad860c0d53f8c to your computer and use it in GitHub Desktop.
y.swift
// Y-combinator in Swift.
func Y<y,⒴>(𝖸:((y)->⒴)->((y)->⒴))->((y)->⒴){
var Y:((y)->⒴)!;Y=𝖸{Y($0)};return Y
}
// Couldn't find a way to avoid such explicitness.
// If types are defined in the inner function, compiler cannot infer type of 'f'.
let factorial = Y {(f:((Int)->Int)) -> ((Int)->Int) in
return {n in
return n == 0 ? 1 : n*f(n-1)
}
}
for i in 0...6 {
println("factorial(\(i)) = \(factorial(i))");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment