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

David Waite david at alkaline-solutions.com
Fri Dec 11 23:46:00 CST 2015


It is tough to give examples which are suitably approachable, illustrative, and complex. Perhaps the Fibonacci sequence:

generator func fibonacci() -> Int {
   var = 0, j = 1
   repeat {
      (i, j) = (j, i + j)
      yield i
   }
}

In addition to being a more complex problem, the sequence is also infinite. Luckily the functional influences on sequences let you deal with that without issue:

// print the first 25 numbers in the fibonacci sequence
fibonacci().prefix(25).forEach { print($0) }

-DW

> On Dec 11, 2015, at 6:38 PM, Kametrixom Tikara <kametrixom at icloud.com> wrote:
> 
> What exactly is the difference to just returning a sequence?
> 
> func helloGenerator(name : String?) -> [String] {
>     return [
>         "Hello",
>         name ?? "World"
>     ]
> }
> 
> for str in helloGenerator("David") {
>     print(str)
> }
> 
> And if you want if lazy:
> 
> func helloGenerator(name : String?) -> LazyCollection<[String]> {
>     return [
>         "Hello",
>         name ?? "World"
>     ].lazy
> }

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151211/0fb12aad/attachment.html>


More information about the swift-evolution mailing list