[swift-evolution] [Proposal] Random Unification

Dave Abrahams dabrahams at apple.com
Tue Jan 9 13:05:59 CST 2018



> On Jan 9, 2018, at 11:01 AM, Ben Cohen via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
> 
>> On Jan 9, 2018, at 2:12 AM, Jonathan Hull via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>> - Why bother supporting non-closed Ranges at all?  If you only allow closed ranges, then you can’t end up with an empty range. The only difference in behavior I can think of is on floating point, but I can’t think of a use-case where excluding the supremum is actually useful in any real world way.
>> 
> 
> 
> Ranges are the currency type, whereas closed ranges aren’t. We should try to avoid any solution that goes against this pattern. People are going to have a Range, and having to convert it into a ClosedRange just to get a random number from it is confusing.
> 
> The argument goes that you want to avoid traps, therefore forbid half-open range because it can be empty and might trap, whereas closed ranges doesn’t. Therefore, let’s only have closed ranges. Type safety ftw. 
> 
> In practice, I don’t think this is justified. Realistically, you can divide uses into two cases, literals and runtime-generated ranges.
> 
> Literals are obviously empty by inspection. It’s hard to do this by accident and any kind of coverage testing of (0..<0).random() will immediately trap. So probably a non-issue.
> 
> If you’re generating ranges at runtime from variables, you have another risk of traps that applies just as much to closed ranges: inversion.
> 
> i.e.:
> 
> x = 5
> y = 4
> x...y // boom, can't form Range with upperBound < lowerBound
> 
> This is easily done. Nate’s example playground even had a possible case!
> 
> // better hope items always has at least 3 elements...
> let countForSale = (3...items.count).random() 
> 
> Given this is already an issue, the additional risk of trapping on empty half-open ranges seems modest and acceptable to me, compared to the alternative of encouraging constant banging of the result from .random() on ranges.

+1


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20180109/3b339d6b/attachment.html>


More information about the swift-evolution mailing list