Skip to content

Instantly share code, notes, and snippets.

@Zeta611
Created August 9, 2022 12:53
Show Gist options
  • Save Zeta611/d4f2e27e5587601fc1a25e7b43bee65d to your computer and use it in GitHub Desktop.
Save Zeta611/d4f2e27e5587601fc1a25e7b43bee65d to your computer and use it in GitHub Desktop.
[Fixed-point combinator in Swift] Fixed-point combinator (Z combinator) in Swift. Y combinator is not available, as Swift is a strict language. #demo
struct Fix<T> {
let x: (Fix<T>) -> T
}
func fix<T, U>(f: @escaping (@escaping (T) -> U) -> ((T) -> U)) -> (T) -> U {
{ _fix in
f { (_fix.x(_fix))($0) }
}(
Fix { _fix in
f { (_fix.x(_fix))($0) }
}
)
}
let factorial: (Int) -> Int = fix { f in { n in n <= 0 ? 1 : n * f(n - 1) } }
print(factorial(10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment