I agree that rand.Shuffle could have used an interface type that's a
subset of sort.Interface. I'm not sure why it didn't, although of
course it's easy to go from one to the other:

    func main() {
        x := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
        xi := sort.IntSlice(x)
        rand.Shuffle(xi.Len(), xi.Swap)
        fmt.Println(x)
    }

As for passing the slice directly, I think it's better to keep APIs
type-safe, at least to start with.
If we find ourselves writing out the swap function many times, then we
could add a rand.ShuffleSlice function along the same lines as
sort.Slice:

    func ShuffleSlice(x interface{}) {
        rand.Shuffle(reflect.ValueOf(x).Len(), reflect.Swapper(x))
    }

As others have pointed out, this is strictly less powerful than the
current rand.Shuffle. For example, you can't shuffle two slices at
once (not that uncommon if you're storing data column-oriented for
cache friendliness).
On Tue, 16 Oct 2018 at 05:29, Dan Kortschak
<dan.kortsc...@adelaide.edu.au> wrote:
>
> ¡left off the Len method!
>
> type Swapper interface {
> // Swap swaps the elements i and j.
> Swap(i, j int)
>
> // Len returns the number of elements that may be swapped.
> Len() int
> }
>
> func Shuffle(s Swapper)
>
> On Tue, 2018-10-16 at 03:46 +0000, Dan Kortschak wrote:
> > type Swapper interface {
> > // Swap swaps the elements i and j.
> > Swap(i, j int)
> > }
> >
> > func Shuffle(s Swapper)
> >
> > On Mon, 2018-10-15 at 19:58 -0700, Bakul Shah wrote:
> > >
> > > On Mon, 15 Oct 2018 20:39:11 -0600 andrey mirtchovski <mirtchovski@
> > > gm
> > > ail.com> wrote:
> > > >
> > > >
> > > > >
> > > > >
> > > > > May be it ought to be called FYShuffle?
> > > > then we'ld have to rename it if we switched the algorithm (which
> > > > has
> > > > happened once for sort.Sort already). that's not what go is about
> > > > :)
> > > Unlikely :-)
> > >
> > > The following is much less obscure.
> > >
> > >     func Shuffle(slice inteface{})
> > >
> > > & might have more more sense. e.g.
> > >
> > > var cards []card
> > > ...
> > > rand.Shuffle(cards)
> > >
> > >
> > > The current Shuffle is confusing. May be because it has a
> > > somewhat clumsy interface.
> > >
> > > >
> > > >
> > > > maybe you're advocating for implementing a Shuffle interface,
> > > > which
> > > > brings us round about to where we are right now :)
> > > I'll shuffle off now....
>
> --
> You received this message because you are subscribed to the Google Groups 
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to