Created
August 9, 2022 12:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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