Swift Sequences and Lazy Evaluation
scottlogic.com
scottlogic.com
let Fibbonacci = SequenceOf {
var current = -1, last = 0
return GeneratorOf {
if current == -1 {
current = 0
} else if current == 0 {
current = 1
} else {
var next = last + current
last = current
current = next
}
return current
}
} let Fibbonacci = SequenceOf {
var current = 0, next = 1
return GeneratorOf {
var ret = current
current = next
next = next + ret
return ret
}
}the syntax is similar to the old school BASIC for loop, but the implementation is heavier in the vast majority of cases where you write simple code for the loop body (i.e. avoiding heavyweight language constructs). Of course unless the compiler optimised out the lazy evaluations...
i would like laziness in this situation to be described by a keyword please, so that i don't have a whole language feature being slower by premature optimisation I don't get a say in... :)
When you use for-in to iterate over arrays, strings, dictionaries etc ... it is an iteration of the type you are no doubt familiar with, where you are iterating over some fixed pre-computed structure.
However, sequences can also generate their 'next' value lazily.
It is something that I consider to be an interesting topic, but would certainly not advocate that everything should become a lazy operation.
Rust uses the exact same external iterator pattern[0] yet is competitive with[1] a C-style for loop[2]
[0] http://doc.rust-lang.org/std/iter/
[1] up to and including inlining and full unrolling
[2] http://www.reddit.com/r/rust/comments/2957fg/can_i_request_a...