簡體   English   中英

在 ScalaCheck 中生成任意 Function1

[英]Generate arbitrary Function1 in ScalaCheck

對於我的測試,我想生成String => Boolean類型的任意隨機函數。

是否可以使用 ScalaCheck 做到這一點?

是的,就像您生成其他類型的任意值一樣:

import org.scalacheck._

// Int instead of Boolean to better see that it is a function
val arb = implicitly[Arbitrary[String => Int]].arbitrary.sample.get

println(arb("a"))
println(arb("a")) // same
println(arb("b"))

因為有一個隱式的Cogen[String]和一個Arbitrary[Boolean] Cogen沒有記錄在用戶指南中,但它等同於CoArbitraryCoArbitrary ,在https://kseo.github.io/posts/2016-12-14-how-quick-check-generate-random-functions.html 中有解釋和https://begriffs.com/posts/2017-01-14-design-use-quickcheck.html (在“CoArbitrary and Gen (a -> b)”下)。

那么是否有可能從隨機案例類生成任意函數? 例如

case class File(name: Str, size:Long)

定義一個Cogen[File]就足夠了。 手動:

implicit val cogenFile: Cogen[File] = Cogen { 
  (seed: Seed, file: File) => Cogen.perturbPair(seed, (file.name, file.size))
}

代碼略多,但概括為 2 個以上的字段:

implicit val cogenFile: Cogen[File] = Cogen { (seed: Seed, file: File) => 
  val seed1 = Cogen.perturb(seed, file.name)
  Cogen.perturb(seed1, file.size)
}

或者自動使用scalacheck-shapeless

implicit val cogenFile: Cogen[File] = MkCogen[File].cogen

我不認為,你需要生成任何東西。 如果你想要一個隨機函數,只需創建一個隨機函數:

    val randomFunction: String => Boolean = _ => Random.nextBoolean 

或者,如果您希望輸出穩定(使用相同參數多次調用同一函數的結果相同):

   def newRandomFunction: String => Boolean =
     mutable.Map.empty[String, Boolean].getOrElseUpdate(_, Random.nextBoolean)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM