scala.util.Random.shuffle的类型是什么?

时间:2014-08-26 09:04:17

标签: scala types functor

背景

我从一个Shuffler类开始做两件事:

  1. 随机播放n:Int索引
  2. 将它们放入n_tranches:Int
  3. 我正在尝试重构这段代码,几乎整个实现都在Trancheur中,后者将索引放入n_tranches。

    例如,我可能想把50张卡片放入6个堆栈中,我称之为分段。

    原始代码

    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)
      }
    }
    

    新代码

    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)
      }
    }
    

    问题

    我希望Shuffler使用仿函数scala.util.Random.shuffle来调用Trancheur。我认为通话很好。

    但是默认情况下,我希望Trancheur拥有一个不做任何事情的身份函子:它只返回与之前相同的结果。我在使用构造函数签名以及定义为标识函数时遇到了问题。

    注意:如果我在调用scala.util.Random.shuffle函数时使用了错误的术语,我会提前道歉 - 这就是我们在C ++中所称的内容。不确定Functor在Scala中是否意味着什么。

1 个答案:

答案 0 :(得分:2)

shuffle是一个功能。所以shuffler(参数)应该期待一个函数。对于您的情况,Seq[Int] => Seq[Int]应该足够了。 Scala还提供预定义的身份功能。

这应该这样做:

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