Hi Mike, > On 27 Oct 2017, at 7:05 pm, Mike Kluev <[email protected]> wrote: > > on Date: Fri, 27 Oct 2017 17:52:54 +0100 Johannes Weiß > <[email protected]> wrote: > > > On 27 Oct 2017, at 6:27 am, Howard Lovatt via swift-evolution > > <[email protected]> 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 > _______________________________________________ swift-evolution mailing list [email protected] https://lists.swift.org/mailman/listinfo/swift-evolution
