[swift-evolution] [Draft]: Introducing a striding(by:) method on 3.0 ranges

Michel Fortin michel.fortin at michelf.ca
Mon Apr 11 16:37:25 CDT 2016


Le 11 avr. 2016 à 14:36, Dave Abrahams <dabrahams at apple.com> a écrit :

> 3. The fact that we're migrating C-style for loops to
>   uses of stride, as noted in https://github.com/apple/swift/pull/2125,
>   has convinced me that, sadly, we may need an answer that doesn't
>   involve ranges.  But maybe something like
> 
>     for x in loop(from: 0.1, while: { $0 < 10 }, next: { $0 + .2 })
> 
>   is sufficient for this purpose.

Please add that. First, it would relieve `stride` from some of the pressure of excelling at replacing existing C-style for loops. But it would also become pretty easy to write custom sequences like this one:

func uniform(start: Double, end: Double, numberOfSteps totalSteps: Int) -> Sequence {
	var currentStep = 0
	return loop(from: start, while: { _ in
		currentStep < totalSteps
	}, next: { _ in
		currentStep += 1
		return start * (Double(totalSteps-currentStep) / Double(totalSteps)) +
			end * (Double(currentStep) / Double(totalSteps))
	})
}

Just don't call the function `loop`, as it does not return a loop.

-- 
Michel Fortin
https://michelf.ca



More information about the swift-evolution mailing list