[swift-evolution] Making capturing semantics of local

Johannes Weiß johannesweiss at apple.com
Sat Oct 28 05:05:53 CDT 2017


Hi Mike,

> On 27 Oct 2017, at 7:05 pm, Mike Kluev <mike.kluev at gmail.com> wrote:
> 
> on Date: Fri, 27 Oct 2017 17:52:54 +0100 Johannes Weiß <johannesweiss at apple.com> wrote:
> 
> > On 27 Oct 2017, at 6:27 am, Howard Lovatt via swift-evolution <swift-evolution at swift.org> wrote:
> >
> > In terms of recursion you can fiddle it:
> >
> > struct RecursiveClosure<C> {
> >     var c: C! = nil
> > }
> > func factorial(_ n: Int) -> Int {
> >     var recursive = RecursiveClosure<(Int) -> Int>()
> >     recursive.c = { x in
> >         (x == 0) ? 1 : x * recursive.c(x - 1)
> >     }
> >     return recursive.c(n)
> > }
> > factorial(5) // 120
> 
> what a hack and a half :)
> 
> sorry, offtopic to the thread but that you can have easier with the fixed-point combinator (https://en.wikipedia.org/wiki/Fixed-point_combinator)
> 
> // the fixed-point combinator
> func fix<T>(_ f: @escaping ((@escaping (T) -> T) -> (T) -> T)) -> (T) -> T {
>     return { (x: T) in (f(fix(f)))(x) }
> }
> 
> // demo
> let fact = fix { fact_ in { n in n == 1 ? 1 : n * fact_(n-1) } }
> for i in 1..<10 {
>     print(fact(i))
> }
> 
> that would be a serious crime against humanity if swift allows this type of code at all :-)

the fixed-point combinator and Y combinator are pretty important in functional languages. And the above code works in Swift. The good thing is that you need to write `fix` only once and you can then use it for all closures that need to be recursive.


-- Johannes

> 
> Mike
> 



More information about the swift-evolution mailing list