[swift-evolution] Making capturing semantics of local
Johannes Weiß
johannesweiss at apple.com
Sun Oct 29 09:02:57 CDT 2017
> On 28 Oct 2017, at 10:14 pm, John McCall <rjmccall at apple.com> wrote:
>
>
>> On Oct 28, 2017, at 6:05 AM, Johannes Weiß via swift-evolution <swift-evolution at swift.org> wrote:
>>
>> 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.
>
> They're important in the theory of functional languages. Anyone seriously promoting using the Y combinator in actual programming instead of using the language's native recursive-binding features is, frankly, someone you should not being taking advice from.
Definitely not arguing with that. But there are (valid?) cases when you want a recursive closure which doesn’t have a native recursion mechanism and then `fix` can be useful I’d argue. I think more straightforward than
>>>> recursive.c = { x in
>>>> (x == 0) ? 1 : x * recursive.c(x - 1)
>>>> }
. But fortunately have local functions, I can only recall wanting a recursive closure once.
— Johannes
>
> John.
>
>> 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
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171029/39a9c98d/attachment.html>
More information about the swift-evolution
mailing list