[swift-evolution] [Proposal] Random Unification

Karl Wagner razielim at gmail.com
Thu Nov 30 07:01:12 CST 2017



> On 28. Nov 2017, at 00:20, Martin Waitz via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hello,
> 
>> Maybe we call the default RNG instance `random`, and then give the `random(in:)` methods another name, like `choose(in:)`?
>> 
>> 	let diceRoll = random.choose(in: 1...6)
>> 	let card = random.choose(in: deck)
>> 	let isHeads = random.choose(in: [true, false])
>> 	let probability = random.choose(in: 0.0...1.0)
>> 	
>> 	let diceRoll = rng.choose(in: 1...6)
>> 	let card = rng.choose(in: deck)
>> 	let isHeads = rng.choose(in: [true, false])
>> 	let probability = rng.choose(in: 0.0...1.0)
> 
> I like this design a lot. After all, `random` is not a property of some type or instance, but we want to generate a new random element within some range/based on some given set.
> Modeling that as methods of the RNG seems to be much more natural.
> 
> -- 
> Martin
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

+1. This discussion seems to have been going on for a long time and I haven’t kept up with all of the arguments, but to me, “random” only makes sense when you’re talking about selecting something from a group.

Some data types, like Int and Bool, have a natural set of all discrete, allowed values, so there is some natural group to talk about which can serve as a reasonable default. Basically, they are similar to enums (remember the discussions we’ve been having about an “allCases” collection for enums? Is there possibly some unifying abstraction between these and types such as Int or Bool?). So I can only really see it looking more or less like this:

protocol RandomNumberGenerator {
    func random<C>(from: C) -> C.Element? where C: Collection
}

// I don’t know; there is probably a real compsci/maths/stats name for this. See ‘enum' discussion.

protocol ClosedValueSet {
    static var allValues: AnyCollection<Self> { get } 
}

extension RandomNumberGenerator {
    func random<T>() -> T? where T: ClosedValueSet {
        return random(from: T.allValues)
    }
}

extension Int: ClosedValueSet {
    static var allValues: AnyCollection<Int> { return AnyCollection(Int.min..<Int.max) }
}

extension Bool: ClosedValueSet {
    static var allValues: AnyCollection<Bool> { return AnyCollection([true, false]) }
}

// …etc

- Karl
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171130/a2c39eec/attachment.html>


More information about the swift-evolution mailing list