Skip to content

Instantly share code, notes, and snippets.

@jubinjacob19
Last active November 4, 2017 04:39
Show Gist options
  • Save jubinjacob19/d8b6636119b10098d326fb7c07e4c473 to your computer and use it in GitHub Desktop.
Save jubinjacob19/d8b6636119b10098d326fb7c07e4c473 to your computer and use it in GitHub Desktop.
The Y combinator in Swift. A single argument Y combinator is used to find the factorial of a number.
import Foundation
func Y<In, Out>(_ f :@escaping (@escaping(In) -> Out) -> (In) -> Out) -> (In) -> Out {
return {
d in f(Y(f))(d)
}
}
let factorial =
Y {(f) in
{ n in
n == 0 ? 1 : n * f(n - 1)
}
}
factorial(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment