[swift-users] Sampling collections

Brent Royal-Gordon brent at architechies.com
Sun Apr 10 20:40:04 CDT 2016


>     import Foundation
>     
>     (1..<4).sample
>     [1,2,3].sample
>     "abc".characters.sample
>     ["a": 1, "b": 2, "c": 3].sample
> 
> Like so many users of Swift, I have extensions of IntegerType, ClosedInterval and CollectionType that avail me of the above methods and their family, but I’d much rather if such extensions came with Darwin or at least Foundation.

I don't think a `sample` property or method is the right approach here. It would be using some sort of global source of random numbers, which means that:

* It's not testable or repeatable
* It needs to be synchronized with other threads
* It can't be configured to use a different random number generator

Personally, I would eventually like to see something like this in the standard library:

	protocol RandomizerProtocol {
		mutating func randomBytes(_ n: Int) -> [UInt8]
		// or possibly something involving a generic-length tuple, for speed
	}
	extension RandomizerProtocol {
		// for coin flips
		mutating func randomChoice() -> Bool { ... }
		// for choosing a random element
		mutating func randomChoice<CollectionType: RandomAccessCollection>(from collection: CollectionType) -> CollectionType.Element { ... }
		// for choosing a random value from an uncountable range (e.g. Range<Double>)
		mutating func randomChoice<Element: Strideable>(from range: Range<Element>) -> Element { ... }
	}
	struct Randomizer: RandomizerProtocol {
		init(state: [UInt8]) { ... }
		init() { self.init(state: somethingToMakeAGoodRandomState()) }

		mutating func randomBytes(_ n: Int) -> [UInt8] {
			// akin to arc4random()
		}
	}

This would allow you to confine a random number generator to a particular thread, swap one implementation for another, or inject one with a fixed starting state as a dependency to make tests predictable. A design like this one works around the problems I described nicely.

However, I don't think this is a high enough priority to address right now. This is borderline out-of-scope as "major new library functionality", and there's so much stuff to do that is truly core to the language, this simply seems like a distraction.
		
-- 
Brent Royal-Gordon
Architechies



More information about the swift-users mailing list