[swift-evolution] Making capturing semantics of local

Mike Kluev mike.kluev at gmail.com
Fri Oct 27 13:05:50 CDT 2017


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 :-)

Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171027/137a1075/attachment.html>


More information about the swift-evolution mailing list