[英]Behavior of shuffle on Set vs List using scala.util.Random
[英]What is the type for scala.util.Random.shuffle?
背景
我從一個Shuffler類開始做兩件事:
我試圖重構這個代碼,幾乎整個實現都在Trancheur中,它將索引放入n_tranches。
例如,我可能想將50張卡放入6個堆棧中,我稱之為tranches。
原始代碼
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
調用scala.util.Random.shuffle
。 我覺得這個電話很好。
但作為默認值,我希望Trancheur擁有一個不執行任何操作的標識函數:它只返回與之前相同的結果。 我遇到了構造函數簽名以及定義為身份函子的問題。
注意:如果我在調用scala.util.Random.shuffle
函數時使用了錯誤的術語,我會事先道歉 - 這就是我們在C ++中所稱的。 不確定Functor在Scala中是否意味着其他內容。
shuffle
是一種功能。 所以shuffler(參數)應該期待一個函數。 對於您的情況, Seq[Int] => Seq[Int]
應該足夠了。 Scala還提供預定義的身份功能。
這應該這樣做:
class Trancheur( n:Int, n_tranches:Int, shuffler: Seq[Int] => Seq[Int] = identity)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.