[swift-evolution] Proposal: Add generator functions to the language
ilya
ilya.nikokoshev at gmail.com
Sat Dec 12 04:54:09 CST 2015
I'm still not sold on the generate keyword; this syntax (once it works)
seems clear enough for me:
func fibonacci() -> SequenceType<Int> {
var (i, j) = (0, 1)
repeat {
(i, j) = (j, i + j)
yield i
}
}
The intent is hard to miss: this function returns something that satisfies
a specialization of SequenceType to type Int. The function can do this
either
(1) by returning a valid SequenceType struct/class object,
(2) by doing a simple return, in which case compiler impements an empty
sequence behind the scenes, or
(3) by inserting a few yield operators before doing (1) or (2), in which
case the compiler creates an appropriate generator struct
Whether the function goes the route (1), (2) or (3) is an implementation
detail of no import to its users.
On Sat, Dec 12, 2015 at 8:46 AM, David Waite via swift-evolution <
swift-evolution at swift.org> wrote:
> 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
> }
>
>
>
> _______________________________________________
> 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/20151212/ec637aff/attachment.html>
More information about the swift-evolution
mailing list