> On Nov 30, 2017, at 3:46 PM, Martin Waitz <t...@admingilde.org> wrote:
> 
> Hello Jonathan,
> 
>> For collections, I think we should call returning a random element 
>> -randomElement, and choosing a random element without replacement 
>> -popRandomElement
> 
> I disagree because I don’t think that the random data is a property of the 
> collection.
> The collection is not the subject which has random elements, it’s more the 
> object which is used when drawing an element.

The collection is a subject which has elements, and we are asking for one of 
them at random.


>> var list = [1,2,3,4]
>> let a:Int? = list.randomElement //List is still [1,2,3,4] and ‘a’ contains 
>> one of the elements
> 
> Instead I would prefer to have something like:
> 
> let a = random.draw(from: list)

But now the RNG has to understand the concept of collections. I would argue it 
is much cleaner to write an extension on Collection.

func randomElement(using source: RandomSource = .default) -> Element? {
        guard !isEmpty else {return nil}
        let idx = Int.random(in: 0…(count - 1), using: source)
        return self[idx]
}

> 
>> let b:Int? = list.popRandomElement //Now list contains all the elements 
>> except the one in ‚b’
> 
> we already have remove(at:), this can be used trivially:
> 
> let b = list.remove(at: random.draw(from: list.indices))
> 
> a little bit more verbose, but easily understandable.
> It uses well known building blocks and does not increase the API surface of 
> collections.

True.  But you could make the same argument for popLast().

I think both are common enough use-cases that they warrant the convenience 
method.  If not though, I can just add it myself for my own code.

Thanks,
Jon


_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to