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 :-) Mike
_______________________________________________ swift-evolution mailing list [email protected] https://lists.swift.org/mailman/listinfo/swift-evolution
