2012-05-09 51 views
16

考虑一个类别的定义如下:高阶ScalaCheck

trait Category[~>[_, _]] { 
    def id[A]: A ~> A 
    def compose[A, B, C](f: A ~> B)(g: B ~> C): A ~> C 
} 

下面是一元函数实例:

object Category { 
    implicit def fCat = new Category[Function1] { 
    def id[A] = identity 
    def compose[A, B, C](f: A => B)(g: B => C) = g.compose(f) 
    } 
} 

现在,种类都受到一些法律。关于成分(.)和身份(id):

forall f: categoryArrow -> id . f == f . id == f 

我想ScalaCheck对此进行测试。让我们尝试对功能在整数:

"Categories" should { 
    import Category._ 

    val intG = { (_ : Int) - 5 } 

    "left identity" ! check { 
    forAll { (a: Int) => fCat.compose(fCat.id[Int])(intG)(a) == intG(a) }  
    } 

    "right identity" ! check { 
    forAll { (a: Int) => fCat.compose(intG)(fCat.id)(a) == intG(a) }  
    } 
} 

但是,这些被量化过(我)特定类型(Int),及(ii)特定功能(intG)。所以这里是我的问题:在推广上述测试方面我能走多远,以及如何?或者换句话说,是否可以创建任意A => B函数的生成器,并将这些函数提供给ScalaCheck?

+2

我不知道你的问题的确切答案,但它让我想起了scalaz中单子法的检查。也许你可以从https://github.com/scalaz/scalaz/blob/master/tests/src/test/scala/scalaz/MonadTest.scala –

+2

获取灵感,也许http://stackoverflow.com/users/53013/daniel -c-sobral知道答案吗? –

+1

如果类型是任意选择的,那么您可以将其视为通过Hilbert's epsilon的通用量化。请参阅https://gist.github.com/2659013。 –

回答

5

不知道Hilbert的epsilon究竟是什么,我会采取更基本的方法,并使用ScalaCheck的ArbitraryGen来选择要使用的函数。

首先,为您要生成的函数定义一个基类。通常,可以生成未定义结果的函数(例如除以零),因此我们将使用PartialFunction作为我们的基类。

trait Fn[A, B] extends PartialFunction[A, B] { 
    def isDefinedAt(a: A) = true 
} 

现在你可以提供一些实现。覆盖toString ScalaCheck的错误信息是可以理解的。

object Identity extends Fn[Int, Int] { 
    def apply(a: Int) = a 
    override def toString = "a" 
} 
object Square extends Fn[Int, Int] { 
    def apply(a: Int) = a * a 
    override def toString = "a * a" 
} 
// etc. 

我选择从二进制函数使用case类生成一元函数,将附加参数传递给构造函数。不是唯一的办法,但我觉得它是最直接的。

case class Summation(b: Int) extends Fn[Int, Int] { 
    def apply(a: Int) = a + b 
    override def toString = "a + %d".format(b) 
} 
case class Quotient(b: Int) extends Fn[Int, Int] { 
    def apply(a: Int) = a/b 
    override def isDefinedAt(a: Int) = b != 0 
    override def toString = "a/%d".format(b) 
} 
// etc. 

现在,您需要创建Fn[Int, Int]发电机,并定义为隐Arbitrary[Fn[Int, Int]]。你可以不断添加生成器,直到你在脸上呈蓝色(多项式,从简单的函数构成复杂的函数等等)。

val funcs = for { 
    b <- arbitrary[Int] 
    factory <- Gen.oneOf[Int => Fn[Int, Int]](
    Summation(_), Difference(_), Product(_), Sum(_), Quotient(_), 
    InvDifference(_), InvQuotient(_), (_: Int) => Square, (_: Int) => Identity) 
} yield factory(b) 

implicit def arbFunc: Arbitrary[Fn[Int, Int]] = Arbitrary(funcs) 

现在您可以定义您的属性。使用intG.isDefinedAt(a)来避免未定义的结果。

property("left identity simple funcs") = forAll { (a: Int, intG: Fn[Int, Int]) => 
    intG.isDefinedAt(a) ==> (fCat.compose(fCat.id[Int])(intG)(a) == intG(a)) 
} 

property("right identity simple funcs") = forAll { (a: Int, intG: Fn[Int, Int]) => 
    intG.isDefinedAt(a) ==> (fCat.compose(intG)(fCat.id)(a) == intG(a)) 
} 

虽然我已经证明只是概括测试的功能,希望这会给你如何使用先进的类型系统欺骗概括了类型的想法。