[swift-evolution] [Proposal] Random Unification

Brent Royal-Gordon brent at architechies.com
Fri Nov 17 19:11:11 CST 2017


> On Nov 17, 2017, at 3:09 PM, Xiaodi Wu via swift-evolution <swift-evolution at swift.org> wrote:
> 
> But actually, Int.random followed by % is the much bigger issue and a very good cautionary tale for why T.random is not a good idea. Swift should help users do the correct thing, and getting a random value across the full domain and computing an integer modulus is never the correct thing to do because of modulo bias, yet it's a very common error to make. We are much better off eliminating this API and encouraging use of the correct API, thereby reducing the likelihood of users making this category of error.

Amen.

> If (and I agree with this) the range-based notation is less intuitive (0..<10.random is certainly less discoverable than Int.random), then we ought to offer an API in the form of `Int.random(in:)` but not `Int.random`. This does not preclude a `Collection.random` API as Alejandro proposes, of course, and that has independent value as Gwendal says.


If we're not happy with the range syntax, maybe we should put `random(in:)`-style methods on the RNG protocol as extension methods instead. Then there's a nice, uniform style:

	let diceRoll = rng.random(in: 1...6)
	let card = rng.random(in: deck)
	let isHeads = rng.random(in: [true, false])
	let probability = rng.random(in: 0.0...1.0)	// Special FloatingPoint overload

The only issue is that this makes the default RNG's name really important. Something like:

	DefaultRandom.shared.random(in: 1...6)

Will be a bit of a pain for users.

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)

This would allow us to keep the default RNG's type private and expose it only as an existential—which means more code will treat RNGs as black boxes, and people will extend the RNG protocol instead of the default RNG struct—while also putting our default random number generator under the name `random`, which is probably where people will look for such a thing.

-- 
Brent Royal-Gordon
Architechies

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


More information about the swift-evolution mailing list