What is the type of scala.util.Random.shuffle?

Background

I started with the Shuffler class, which does two things:

  • Shuffle n: Int indices
  • Inserts them into n_tranches: Int

I'm trying to refactor this code in such a way that almost all of the implementation is in Trancheur, which puts the indices in n_tranches.

For example, I can put 50 cards in 6 stacks, which I call tranches.

Original code

class Shuffler( n:Int, n_tranches:Int )
{
  val v = scala.util.Random.shuffle( (0 to n-1).toVector )
  // returns tranche[0,n_tranches-1] which we live in
  def tranche( i:Int ) = idxs(i).map( v ).sorted.toVector

  private val idxs = cut( 0 to (n-1), n_tranches ).toVector
  private def cut[A](xs: Seq[A], n: Int) = {
    val (quot, rem) = (xs.size / n, xs.size % n)
    val (smaller, bigger) = xs.splitAt(xs.size - rem * (quot + 1))
    smaller.grouped(quot) ++ bigger.grouped(quot + 1)
  }
}

      

New code

class Shuffler( n:Int, n_tranches:Int )
  extends Trancheur( n, n_tranches, scala.util.Random.shuffle )
{
}

class Trancheur( n:Int, n_tranches:Int, shuffler )     // WHAT SHOULD I PUT HERE?!?!?!?
{
  val v = shuffler( (0 to n-1).toVector )
  // returns tranche[0,n_tranches-1] which we live in
  def tranche( i:Int ) = idxs(i).map( v ).sorted.toVector

  private val idxs = cut( 0 to (n-1), n_tranches ).toVector
  private def cut[A](xs: Seq[A], n: Int) = {
    val (quot, rem) = (xs.size / n, xs.size % n)
    val (smaller, bigger) = xs.splitAt(xs.size - rem * (quot + 1))
    smaller.grouped(quot) ++ bigger.grouped(quot + 1)
  }
}

      

Problem

I want Shuffler to call Trancheur with a functor scala.util.Random.shuffle

. I think the call is fine.

But by default, I want Trancheur to have an identity functor that does nothing: it just returns the same results as before. I'm having problems with the signature of the constructor and what needs to be defined as the identity functor.

NOTE. I apologize in advance if I used the wrong term when calling the scala.util.Random.shuffle

functor - this is what we call it in C ++. Not sure if Functor means anything else in Scala.

+3


source to share


1 answer


shuffle

is a function. Therefore shuffler (parameter) must wait for a function. It Seq[Int] => Seq[Int]

should be enough for your case . Scala also provides a predefined identity function.

This should do it:



class Trancheur( n:Int, n_tranches:Int, shuffler: Seq[Int] => Seq[Int] = identity)

      

+2


source







All Articles