【问题标题】:Generate arbitrary Function1 in ScalaCheck在 ScalaCheck 中生成任意 Function1
【发布时间】:2020-01-15 17:09:38
【问题描述】:

对于我的测试,我想生成String => Boolean 类型的任意随机函数。

是否可以使用 ScalaCheck 做到这一点?

【问题讨论】:

    标签: scala scalacheck


    【解决方案1】:

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

    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 没有记录在用户指南中,但它等同于 QuickCheck 的 CoArbitrary,在 https://kseo.github.io/posts/2016-12-14-how-quick-check-generate-random-functions.htmlhttps://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
    

    【讨论】:

    • 那么有可能从随机案例类生成任意函数吗?例如case class File(name: Str, size:Long) val arb = implicitly[Arbitrary[File => Int]].arbitrary.sample.get
    【解决方案2】:

    我不认为,你需要生成任何东西。如果你想要一个随机函数,只需创建一个随机函数:

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

    或者如果您希望输出稳定(使用相同参数多次调用同一函数的相同结果):

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 2013-11-18
      • 2011-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多