[swift-evolution] Proposal: Add generator functions to the language

Taras Zakharko taras.zakharko at uzh.ch
Sat Dec 12 22:43:52 CST 2015


Personally, I am agains generators (its quite specific syntactic sugar that adds a lot of complexity), but I would be all for a comprehensive coroutine library*. One can model it after Lua’s coroutines (http://www.lua.org/pil/9.1.html), which works well with the existing syntax. Your example becomes something like:

helloGenerator = Coroutine.create<()->String>({name:String -> () in 
   Coroutine.yield(“Hello”)
   Coroutine.yield(name ?? “World”)
})

this generates a class instance with a resume ()->String? method that can be used to retrieve the values. You can also pass values via resume (they will be then available as results of coroutine.yield)

One can than use helloGenerator.resume() to get the values (which can be easily wrapped in a sequence etc).

Benefits of this approach: no need for significant syntactic change (although a coroutine keyword could be introduced instead of func to wrap the above declaration), the coroutine functions are offloaded to a type rather than syntactic construct, type safety is quite easy to preserve. Still, its far from being a trivial thing to implement as it would require support of continuations on the compiler level. 

Cheers, 

 Taras

*Yes, current generators in Python are essentially coroutines but I think it important to keep the terminology clean. Generators are intended first and foremost as lazy sequence, well, generators. Coroutines are a much more versatile construct. 



On Fri, Dec 11, 2015 at 18:21 PM, David Waite via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
Looking for feedback on crafting a proposal adding generator functions to Swift. I understand this will likely be a very involved proposal at the language level, although I actually don’t know the complexity of the change within the Swift compiler itself.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151213/16ef7bb7/attachment.html>


More information about the swift-evolution mailing list