Compare commits

...

No commits in common. "codecs" and "quickcheck" have entirely different histories.

11 changed files with 345 additions and 485 deletions

View File

@ -26,7 +26,7 @@ grade:
tags: tags:
- cs210 - cs210
image: image:
name: registry.gitlab.com/fnux/cs210-grading-images/progfun2-codecs:20191027-dfbea8aed96096ed3af1cf1958549b97328d4c25 name: registry.gitlab.com/fnux/cs210-grading-images/progfun2-quickcheck:20191030-a3e376e6385659be92ad7972a94c2f289fdfafb7
entrypoint: [""] entrypoint: [""]
allow_failure: true allow_failure: true
before_script: before_script:

View File

@ -1,6 +1,7 @@
# CS-210: Codecs # CS-210: Quickcheck
Please follow the [instructions from the main course Please follow the [instructions from the main course
respository](https://gitlab.epfl.ch/lamp/cs-210-functional-programming-2019/blob/master/week11/00-homework8.md). respository](https://gitlab.epfl.ch/lamp/cs-210-functional-programming-2019/blob/master/week7/00-homework6.md).
Grading and submission details can be found [here](https://gitlab.epfl.ch/lamp/cs-210-functional-programming-2019/blob/master/week1/02-grading-and-submission.md). Grading and submission details can be found [here](https://gitlab.epfl.ch/lamp/cs-210-functional-programming-2019/blob/master/week1/02-grading-and-submission.md).

View File

@ -1,16 +1,11 @@
course := "progfun2" course := "progfun2"
assignment := "codecs" assignment := "quickcheck"
name := course.value + "-" + assignment.value name := course.value + "-" + assignment.value
testSuite := "codecs.CodecsSuite" testSuite := "quickcheck.QuickCheckSuite"
scalaVersion := "0.19.0-RC1" scalaVersion := "0.19.0-RC1"
scalacOptions ++= Seq("-deprecation") scalacOptions ++= Seq("-language:implicitConversions", "-deprecation")
libraryDependencies ++= Seq( libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % Test
("org.scalacheck" %% "scalacheck" % "1.14.2" % Test).withDottyCompat(scalaVersion.value), libraryDependencies += ("org.scalacheck" %% "scalacheck" % "1.14.2").withDottyCompat(scalaVersion.value)
("org.typelevel" %% "jawn-parser" % "0.14.2").withDottyCompat(scalaVersion.value),
"com.novocode" % "junit-interface" % "0.11" % Test
)
testOptions in Test += Tests.Argument(TestFrameworks.JUnit, "-a", "-v", "-s") testOptions in Test += Tests.Argument(TestFrameworks.JUnit, "-a", "-v", "-s")
initialCommands in console := """import codecs.{_, given}"""

Binary file not shown.

View File

@ -1,283 +0,0 @@
package codecs
/**
* A data type modeling JSON values.
*
* For example, the `42` integer JSON value can be modeled as `Json.Num(42)`
*/
sealed trait Json {
/**
* Try to decode this JSON value into a value of type `A` by using
* the given decoder.
*
* Note that you have to explicitly fix `A` type parameter when you call the method:
*
* {{{
* someJsonValue.decodeAs[User] // OK
* someJsonValue.decodeAs // Wrong!
* }}}
*/
def decodeAs[A](given decoder: Decoder[A]): Option[A] = decoder.decode(this)
}
object Json {
/** The JSON `null` value */
case object Null extends Json
/** JSON boolean values */
case class Bool(value: Boolean) extends Json
/** JSON numeric values */
case class Num(value: BigDecimal) extends Json
/** JSON string values */
case class Str(value: String) extends Json
/** JSON objects */
case class Obj(fields: Map[String, Json]) extends Json
/** JSON arrays */
case class Arr(items: List[Json]) extends Json
}
/**
* A type class that turns a value of type `A` into its JSON representation.
*/
trait Encoder[-A] {
def encode(value: A): Json
/**
* Transforms this `Encoder[A]` into an `Encoder[B]`, given a transformation function
* from `B` to `A`.
*
* For instance, given a `Encoder[String]`, we can get an `Encoder[UUID]`:
*
* {{{
* def uuidEncoder(given stringEncoder: Encoder[String]): Encoder[UUID] =
* stringEncoder.transform[UUID](uuid => uuid.toString)
* }}}
*
* This operation is also known as ?contramap?.
*/
def transform[B](f: B => A): Encoder[B] =
Encoder.fromFunction[B](value => this.encode(f(value)))
}
object Encoder extends GivenEncoders {
/**
* Convenient method for creating an instance of encoder from a function `f`
*/
def fromFunction[A](f: A => Json) = new Encoder[A] {
def encode(value: A): Json = f(value)
}
}
trait GivenEncoders {
/** An encoder for the `Unit` value */
given Encoder[Unit] = Encoder.fromFunction(_ => Json.Null)
/** An encoder for `Int` values */
given Encoder[Int] = Encoder.fromFunction(n => Json.Num(BigDecimal(n)))
/** An encoder for `String` values */
given Encoder[String] =
Encoder.fromFunction(str => Json.Str(str))
/** An encoder for `Boolean` values */
given Encoder[Boolean] =
Encoder.fromFunction(v => Json.Bool(v))
/**
* Encodes a list of values of type `A` into a JSON array containing
* the list elements encoded with the given `encoder`
*/
given [A](given encoder: Encoder[A]): Encoder[List[A]] =
Encoder.fromFunction(as => Json.Arr(as.map(encoder.encode)))
}
/**
* A specialization of `Encoder` that returns JSON objects only
*/
trait ObjectEncoder[-A] extends Encoder[A] {
// Refines the encoding result to `Json.Obj`
def encode(value: A): Json.Obj
/**
* Combines `this` encoder with `that` encoder.
* Returns an encoder producing a JSON object containing both
* fields of `this` encoder and fields of `that` encoder.
*/
def zip[B](that: ObjectEncoder[B]): ObjectEncoder[(A, B)] =
ObjectEncoder.fromFunction { (a, b) =>
Json.Obj(this.encode(a).fields ++ that.encode(b).fields)
}
}
object ObjectEncoder {
/**
* Convenient method for creating an instance of object encoder from a function `f`
*/
def fromFunction[A](f: A => Json.Obj): ObjectEncoder[A] = new ObjectEncoder[A] {
def encode(value: A): Json.Obj = f(value)
}
/**
* An encoder for values of type `A` that produces a JSON object with one field
* named according to the supplied `name` and containing the encoded value.
*/
def field[A](name: String)(given encoder: Encoder[A]): ObjectEncoder[A] =
ObjectEncoder.fromFunction(a => Json.Obj(Map(name -> encoder.encode(a))))
}
/**
* The dual of an encoder. Decodes a serialized value into its initial type `A`.
*/
trait Decoder[+A] {
/**
* @param data The data to de-serialize
* @return The decoded value wrapped in `Some`, or `None` if decoding failed
*/
def decode(data: Json): Option[A]
/**
* Combines `this` decoder with `that` decoder.
* Returns a decoder that invokes both `this` decoder and `that`
* decoder and returns a pair of decoded value in case both succeed,
* or `None` if at least one failed.
*/
def zip[B](that: Decoder[B]): Decoder[(A, B)] =
Decoder.fromFunction { json =>
this.decode(json).zip(that.decode(json))
}
/**
* Transforms this `Decoder[A]` into a `Decoder[B]`, given a transformation function
* from `A` to `B`.
*
* This operation is also known as ?map?.
*/
def transform[B](f: A => B): Decoder[B] =
Decoder.fromFunction(json => this.decode(json).map(f))
}
object Decoder extends GivenDecoders {
/**
* Convenient method to build a decoder instance from a function `f`
*/
def fromFunction[A](f: Json => Option[A]): Decoder[A] = new Decoder[A] {
def decode(data: Json): Option[A] = f(data)
}
/**
* Alternative method for creating decoder instances
*/
def fromPartialFunction[A](pf: PartialFunction[Json, A]): Decoder[A] =
fromFunction(pf.lift)
}
trait GivenDecoders {
/** A decoder for the `Unit` value */
given Decoder[Unit] =
Decoder.fromPartialFunction { case Json.Null => () }
/** A decoder for `Int` values. Hint: use the `isValidInt` method of `BigDecimal`. */
// TODO Define a given `Decoder[Int]` instance
given Decoder[Int] =
Decoder.fromFunction{ case Json.Num(v) => if v.isValidInt then Some(v.intValue) else None
case _ => None}
/** A decoder for `String` values */
// TODO Define a given `Decoder[String]` instance
given Decoder[String] =
Decoder.fromPartialFunction{ case Json.Str(str) => str}
/** A decoder for `Boolean` values */
// TODO Define a given `Decoder[Boolean]` instance
given Decoder[Boolean] =
Decoder.fromPartialFunction{ case Json.Bool(v) => v}
/**
* A decoder for JSON arrays. It decodes each item of the array
* using the given `decoder`. The resulting decoder succeeds only
* if all the JSON array items are successfully decoded.
*/
given [A](given decoder: Decoder[A]): Decoder[List[A]] =
Decoder.fromFunction {
case Json.Arr(items: List[Json]) => Some(items.map(v => decoder.decode(v).get))
case _ => None
}
/**
* A decoder for JSON objects. It decodes the value of a field of
* the supplied `name` using the given `decoder`.
*/
def field[A](name: String)(given decoder: Decoder[A]): Decoder[A] =
Decoder.fromFunction{
case Json.Obj(field: Map[String, Json]) => decoder.decode(field.get(name).get)
case _ => None
}
}
case class Person(name: String, age: Int)
object Person extends PersonCodecs
trait PersonCodecs {
/** The encoder for `Person` */
given Encoder[Person] =
ObjectEncoder.field[String]("name")
.zip(ObjectEncoder.field[Int]("age"))
.transform[Person](user => (user.name, user.age))
/** The corresponding decoder for `Person` */
given Decoder[Person] ={
Decoder.field[String]("name").zip(Decoder.field[Int]("age")).transform[Person](user => Person(user._1, user._2))
}
}
case class Contacts(people: List[Person])
object Contacts extends ContactsCodecs
trait ContactsCodecs {
// TODO Define the encoder and the decoder for `Contacts`
// The JSON representation of a value of type `Contacts` should be
// a JSON object with a single field named ?people? containing an
// array of values of type `Person` (reuse the `Person` codecs)
given Encoder[Contacts] =
ObjectEncoder.field[List[Person]]("people").transform[Contacts](c => c.people)
given Decoder[Contacts] =
Decoder.field[List[Person]]("people").transform[Contacts](p => Contacts(p))
}
// In case you want to try your code, here is a simple `Main`
// that can be used as a starting point. Otherwise, you can use
// the REPL (use the `console` sbt task).
object Main {
def main(args: Array[String]): Unit = {
println(renderJson(42))
println(renderJson("foo"))
val maybeJsonString = parseJson(""" "foo" """)
val maybeJsonObj = parseJson(""" { "name": "Alice", "age": 42 } """)
val maybeJsonObj2 = parseJson(""" { "name": "Alice", "age": "42" } """)
// Uncomment the following lines as you progress in the assignment
println(maybeJsonString.flatMap(_.decodeAs[Int]))
println(maybeJsonString.flatMap(_.decodeAs[String]))
println(maybeJsonObj.flatMap(_.decodeAs[Person]))
println(maybeJsonObj2.flatMap(_.decodeAs[Person]))
println(renderJson(Person("Bob", 66)))
}
}

View File

@ -1,74 +0,0 @@
package codecs
import org.typelevel.jawn.{ Parser, SimpleFacade }
import scala.collection.mutable
import scala.util.Try
// Utility methods that decode values from `String` JSON blobs, and
// render values to `String` JSON blobs
/**
* Parse a JSON document contained in a `String` value into a `Json` value, returns
* `None` in case the supplied `s` value is not a valid JSON document.
*/
def parseJson(s: String): Option[Json] = Parser.parseFromString[Json](s).toOption
/**
* Parse the JSON value from the supplied `s` parameter, and then try to decode
* it as a value of type `A` using the given `decoder`.
*
* Returns `None` if JSON parsing failed, or if decoding failed.
*/
def parseAndDecode[A](s: String)(given decoder: Decoder[A]): Option[A] =
for {
json <- parseJson(s)
a <- decoder.decode(json)
} yield a
/**
* Render the supplied `value` into JSON using the given `encoder`.
*/
def renderJson[A](value: A)(given encoder: Encoder[A]): String =
render(encoder.encode(value))
private def render(json: Json): String = json match {
case Json.Null => "null"
case Json.Bool(b) => b.toString
case Json.Num(n) => n.toString
case Json.Str(s) => renderString(s)
case Json.Arr(vs) => vs.map(render).mkString("[", ",", "]")
case Json.Obj(vs) => vs.map { case (k, v) => s"${renderString(k)}:${render(v)}" }.mkString("{", ",", "}")
}
private def renderString(s: String): String = {
val sb = new StringBuilder
sb.append('"')
var i = 0
val len = s.length
while (i < len) {
s.charAt(i) match {
case '"' => sb.append("\\\"")
case '\\' => sb.append("\\\\")
case '\b' => sb.append("\\b")
case '\f' => sb.append("\\f")
case '\n' => sb.append("\\n")
case '\r' => sb.append("\\r")
case '\t' => sb.append("\\t")
case c =>
if (c < ' ') sb.append("\\u%04x" format c.toInt)
else sb.append(c)
}
i += 1
}
sb.append('"').toString
}
given SimpleFacade[Json] {
def jnull() = Json.Null
def jtrue() = Json.Bool(true)
def jfalse() = Json.Bool(false)
def jnum(s: CharSequence, decIndex: Int, expIndex: Int) = Json.Num(BigDecimal(s.toString))
def jstring(s: CharSequence) = Json.Str(s.toString)
def jarray(vs: List[Json]) = Json.Arr(vs)
def jobject(vs: Map[String, Json]) = Json.Obj(vs)
}

View File

@ -0,0 +1,119 @@
package quickcheck
trait IntHeap extends Heap {
override type A = Int
override def ord = scala.math.Ordering.Int
}
// http://www.brics.dk/RS/96/37/BRICS-RS-96-37.pdf
// Figure 1, page 3
trait Heap {
type H // type of a heap
type A // type of an element
def ord: Ordering[A] // ordering on elements
def empty: H // the empty heap
def isEmpty(h: H): Boolean // whether the given heap h is empty
def insert(x: A, h: H): H // the heap resulting from inserting x into h
def meld(h1: H, h2: H): H // the heap resulting from merging h1 and h2
def findMin(h: H): A // a minimum of the heap h
def deleteMin(h: H): H // a heap resulting from deleting a minimum of h
}
// Figure 3, page 7
trait BinomialHeap extends Heap {
type Rank = Int
case class Node(x: A, r: Rank, c: List[Node])
override type H = List[Node]
protected def root(t: Node) = t.x
protected def rank(t: Node) = t.r
protected def link(t1: Node, t2: Node): Node = // t1.r == t2.r
if ord.lteq(t1.x, t2.x) then
Node(t1.x, t1.r + 1, t2 :: t1.c)
else
Node(t2.x, t2.r + 1, t1 :: t2.c)
protected def ins(t: Node, ts: H): H = ts match
case Nil => List(t)
case tp :: ts => // t.r <= tp.r
if t.r < tp.r then
t :: tp :: ts
else
ins(link(t, tp), ts)
override def empty = Nil
override def isEmpty(ts: H) = ts.isEmpty
override def insert(x: A, ts: H) = ins(Node(x, 0, Nil), ts)
override def meld(ts1: H, ts2: H) = (ts1, ts2) match
case (Nil, ts) => ts
case (ts, Nil) => ts
case (t1 :: ts1, t2 :: ts2) =>
if t1.r < t2.r then
t1 :: meld(ts1, t2 :: ts2)
else if t2.r < t1.r then
t2 :: meld(t1 :: ts1, ts2)
else
ins(link(t1, t2), meld(ts1, ts2))
override def findMin(ts: H) = ts match
case Nil => throw new NoSuchElementException("min of empty heap")
case t :: Nil => root(t)
case t :: ts =>
val x = findMin(ts)
if ord.lteq(root(t), x) then
root(t)
else
x
override def deleteMin(ts: H) = ts match
case Nil => throw new NoSuchElementException("delete min of empty heap")
case t :: ts =>
def getMin(t: Node, ts: H): (Node, H) = ts match
case Nil => (t, Nil)
case tp :: tsp =>
val (tq, tsq) = getMin(tp, tsp)
if ord.lteq(root(t), root(tq)) then
(t, ts)
else
(tq, t :: tsq)
val (Node(_, _, c), tsq) = getMin(t, ts)
meld(c.reverse, tsq)
}
trait Bogus1BinomialHeap extends BinomialHeap {
override def findMin(ts: H) = ts match
case Nil => throw new NoSuchElementException("min of empty heap")
case t :: ts => root(t)
}
trait Bogus2BinomialHeap extends BinomialHeap {
override protected def link(t1: Node, t2: Node): Node = // t1.r == t2.r
if !ord.lteq(t1.x, t2.x) then
Node(t1.x, t1.r + 1, t2 :: t1.c)
else
Node(t2.x, t2.r + 1, t1 :: t2.c)
}
trait Bogus3BinomialHeap extends BinomialHeap {
override protected def link(t1: Node, t2: Node): Node = // t1.r == t2.r
if ord.lteq(t1.x, t2.x) then
Node(t1.x, t1.r + 1, t1 :: t1.c)
else
Node(t2.x, t2.r + 1, t2 :: t2.c)
}
trait Bogus4BinomialHeap extends BinomialHeap {
override def deleteMin(ts: H) = ts match
case Nil => throw new NoSuchElementException("delete min of empty heap")
case t :: ts => meld(t.c.reverse, ts)
}
trait Bogus5BinomialHeap extends BinomialHeap {
override def meld(ts1: H, ts2: H) = ts1 match
case Nil => ts2
case t1 :: ts1 => List(Node(t1.x, t1.r, ts1 ++ ts2))
}

View File

@ -0,0 +1,66 @@
package quickcheck
import org.scalacheck._
import Arbitrary._
import Gen._
import Prop.{BooleanOperators => _, _}
abstract class QuickCheckHeap extends Properties("Heap") with IntHeap {
lazy val genHeap: Gen[H] = for {
a <- arbitrary[Int]
h <- oneOf(const(empty), genHeap)
} yield insert(a, h)
implicit lazy val arbHeap: Arbitrary[H] = Arbitrary(genHeap)
property("min1") = forAll { (a: Int) =>
val h = insert(a, empty)
findMin(h) == a
}
property("gen1") = forAll { (h: H) =>
val m = if isEmpty(h) then 0 else findMin(h)
findMin(insert(m, h)) == m
}
property("smallest") = forAll { (a: Int, b: Int) =>
val h = insert(b, insert(a, empty))
val min = if (a<b) then a else b
if (a==b) true else
findMin(h) == min
}
property("deleteSingle") = forAll { (a: Int) =>
val h = insert(a, empty)
val h1 = deleteMin(h)
isEmpty(h1)
}
def multiMins(h: H, l: List[Int]): List[Int] = {
if (isEmpty(h)) then l
else findMin(h) :: multiMins(deleteMin(h), l)
}
property("multiMins") = forAll { (h1: H) =>
val xs = multiMins(h1, Nil)
xs == xs.sorted
}
property("meldMin") = forAll { (h1: H, h2: H) =>
val min1 = findMin(h1)
val min2 = findMin(h2)
val m = meld(h1, h2)
val minMeld = findMin(m)
minMeld == min1 || minMeld == min2
}
property("meldMinMove") = forAll { (h1: H, h2: H) =>
val meld1 = meld(h1, h2)
val min1 = findMin(h1)
val meld2 = meld(deleteMin(h1), insert(min1, h2))
val xs1 = multiMins(meld1, Nil)
val xs2 = multiMins(meld2, Nil)
xs1 == xs2
}
}

View File

@ -1,115 +0,0 @@
package codecs
import org.scalacheck
import org.scalacheck.{ Gen, Prop }
import org.scalacheck.Prop.propBoolean
import org.junit.{ Assert, Test }
import scala.reflect.ClassTag
class CodecsSuite extends GivenEncoders, GivenDecoders, PersonCodecs, ContactsCodecs, TestEncoders, TestDecoders {
def checkProperty(prop: Prop): Unit = {
val result = scalacheck.Test.check(scalacheck.Test.Parameters.default, prop)
def fail(labels: Set[String], fallback: String): Nothing =
if labels.isEmpty then throw new AssertionError(fallback)
else throw new AssertionError(labels.mkString(". "))
result.status match {
case scalacheck.Test.Passed | _: scalacheck.Test.Proved => ()
case scalacheck.Test.Failed(_, labels) => fail(labels, "A property failed.")
case scalacheck.Test.PropException(_, e, labels) => fail(labels, s"An exception was thrown during property evaluation: $e.")
case scalacheck.Test.Exhausted => fail(Set.empty, "Unable to generate data.")
}
}
/**
* Check that a value of an arbitrary type `A` can be encoded and then successfully
* decoded with the given pair of encoder and decoder.
*/
def encodeAndThenDecodeProp[A](a: A)(given encA: Encoder[A], decA: Decoder[A]): Prop = {
val maybeDecoded = decA.decode(encA.encode(a))
maybeDecoded.contains(a) :| s"Encoded value '$a' was not successfully decoded. Got '$maybeDecoded'."
}
@Test def `it is possible to encode and decode the 'Unit' value (0pts)`(): Unit = {
checkProperty(Prop.forAll((unit: Unit) => encodeAndThenDecodeProp(unit)))
}
@Test def `it is possible to encode and decode 'Int' values (1pt)`(): Unit = {
checkProperty(Prop.forAll((x: Int) => encodeAndThenDecodeProp(x)))
}
@Test def `the 'Int' decoder should reject invalid 'Int' values (2pts)`(): Unit = {
val decoded = summon[Decoder[Int]].decode(Json.Num(4.2))
assert(decoded.isEmpty, "decoding 4.2 as an integer value should fail")
}
@Test def `a 'String' value should be encoded as a JSON string (1pt)`(): Unit = {
assert(summon[Encoder[String]].encode("foo") == Json.Str("foo"))
}
@Test def `it is possible to encode and decode 'String' values (1pt)`(): Unit = {
checkProperty(Prop.forAll((s: String) => encodeAndThenDecodeProp(s)))
}
@Test def `a 'Boolean' value should be encoded as a JSON boolean (1pt)`(): Unit = {
val encoder = summon[Encoder[Boolean]]
assert(encoder.encode(true) == Json.Bool(true))
assert(encoder.encode(false) == Json.Bool(false))
}
@Test def `it is possible to encode and decode 'Boolean' values (1pt)`(): Unit = {
checkProperty(Prop.forAll((b: Boolean) => encodeAndThenDecodeProp(b)))
}
@Test def `a 'List[A]' value should be encoded as a JSON array (0pts)`(): Unit = {
val xs = 1 :: 2 :: Nil
val encoder = summon[Encoder[List[Int]]]
assert(encoder.encode(xs) == Json.Arr(List(Json.Num(1), Json.Num(2))))
}
@Test def `it is possible to encode and decode lists (5pts)`(): Unit = {
checkProperty(Prop.forAll((xs: List[Int]) => encodeAndThenDecodeProp(xs)))
}
@Test def `a 'Person' value should be encoded as a JSON object (1pt)`(): Unit = {
val person = Person("Alice", 42)
val json = Json.Obj(Map("name" -> Json.Str("Alice"), "age" -> Json.Num(42)))
val encoder = summon[Encoder[Person]]
assert(encoder.encode(person) == json)
}
@Test def `it is possible to encode and decode people (4pts)`(): Unit = {
checkProperty(Prop.forAll((s: String, x: Int) => encodeAndThenDecodeProp(Person(s, x))))
}
@Test def `a 'Contacts' value should be encoded as a JSON object (1pt)`(): Unit = {
val contacts = Contacts(List(Person("Alice", 42)))
val json = Json.Obj(Map("people" ->
Json.Arr(List(Json.Obj(Map("name" -> Json.Str("Alice"), "age" -> Json.Num(42)))))
))
val encoder = summon[Encoder[Contacts]]
assert(encoder.encode(contacts) == json)
}
@Test def `it is possible to encode and decode contacts (4pts)`(): Unit = {
val peopleGenerator = Gen.listOf(Gen.resultOf((s: String, x: Int) => Person(s, x)))
checkProperty(Prop.forAll(peopleGenerator)(people => encodeAndThenDecodeProp(Contacts(people))))
}
}
trait TestEncoders extends EncoderFallbackInstance
trait EncoderFallbackInstance {
given [A](given ct: ClassTag[A]): Encoder[A] = throw new AssertionError(s"No given instance of `Encoder[${ct.runtimeClass.getSimpleName}]`")
}
trait TestDecoders extends DecoderFallbackInstance
trait DecoderFallbackInstance {
given [A](given ct: ClassTag[A]): Decoder[A] = throw new AssertionError(s"No given instance of `Decoder[${ct.runtimeClass.getSimpleName}]")
}

View File

@ -0,0 +1,55 @@
package quickcheck
import org.scalacheck.Properties
import org.junit._
import org.scalacheck.Arbitrary._
import org.scalacheck.Prop
import org.scalacheck.Prop.{BooleanOperators => _, _}
import org.scalacheck.Test.{check, Result, Failed, PropException}
object QuickCheckBinomialHeap extends QuickCheckHeap with BinomialHeap
class QuickCheckSuite {
def checkBogus(p: Properties): Unit =
def fail = throw new AssertionError(
s"A bogus heap should NOT satisfy all properties. Try to find the bug!")
check(asProp(p))(identity) match
case r: Result => r.status match
case _: Failed =>
() // OK: scalacheck found a counter example!
case p: PropException =>
p.e match
case e: NoSuchElementException =>
() // OK: the implementation throws NSEE
case _ =>
fail
case _ =>
fail
/** Turns a `Properties` instance into a single `Prop` by combining all the properties */
def asProp(properties: Properties): Prop = Prop.all(properties.properties.map(_._2).toSeq:_*)
@Test def `Binomial heap satisfies properties. (5pts)`: Unit =
Assert.assertTrue(
check(asProp(new QuickCheckHeap with quickcheck.test.BinomialHeap))(identity).passed
)
@Test def `Bogus (1) binomial heap does not satisfy properties. (10pts)`: Unit =
checkBogus(new QuickCheckHeap with quickcheck.test.Bogus1BinomialHeap)
@Test def `Bogus (2) binomial heap does not satisfy properties. (10pts)`: Unit =
checkBogus(new QuickCheckHeap with quickcheck.test.Bogus2BinomialHeap)
@Test def `Bogus (3) binomial heap does not satisfy properties. (10pts)`: Unit =
checkBogus(new QuickCheckHeap with quickcheck.test.Bogus3BinomialHeap)
@Test def `Bogus (4) binomial heap does not satisfy properties. (10pts)`: Unit =
checkBogus(new QuickCheckHeap with quickcheck.test.Bogus4BinomialHeap)
@Test def `Bogus (5) binomial heap does not satisfy properties. (10pts)`: Unit =
checkBogus(new QuickCheckHeap with quickcheck.test.Bogus5BinomialHeap)
@Rule def individualTestTimeout = new org.junit.rules.Timeout(10 * 1000)
}

View File

@ -0,0 +1,96 @@
package quickcheck.test
// Figure 3, page 7
trait BinomialHeap extends quickcheck.Heap {
type Rank = Int
case class Node(x: A, r: Rank, c: List[Node])
override type H = List[Node]
protected def root(t: Node) = t.x
protected def rank(t: Node) = t.r
protected def link(t1: Node, t2: Node): Node = // t1.r == t2.r
if ord.lteq(t1.x, t2.x) then
Node(t1.x, t1.r + 1, t2 :: t1.c)
else
Node(t2.x, t2.r + 1, t1 :: t2.c)
protected def ins(t: Node, ts: H): H = ts match
case Nil => List(t)
case tp :: ts => // t.r<=tp.r
if t.r < tp.r then
t :: tp :: ts
else
ins(link(t, tp), ts)
override def empty = Nil
override def isEmpty(ts: H) = ts.isEmpty
override def insert(x: A, ts: H) = ins(Node(x, 0, Nil), ts)
override def meld(ts1: H, ts2: H) = (ts1, ts2) match
case (Nil, ts) => ts
case (ts, Nil) => ts
case (t1 :: ts1, t2 :: ts2) =>
if t1.r < t2.r then
t1 :: meld(ts1, t2 :: ts2)
else if t2.r < t1.r then
t2 :: meld(t1 :: ts1, ts2)
else
ins(link(t1, t2), meld(ts1, ts2))
override def findMin(ts: H) = ts match
case Nil => throw new NoSuchElementException("min of empty heap")
case t :: Nil => root(t)
case t :: ts =>
val x = findMin(ts)
if ord.lteq(root(t), x) then
root(t)
else
x
override def deleteMin(ts: H) = ts match
case Nil => throw new NoSuchElementException("delete min of empty heap")
case t :: ts =>
def getMin(t: Node, ts: H): (Node, H) = ts match
case Nil => (t, Nil)
case tp :: tsp =>
val (tq, tsq) = getMin(tp, tsp)
if ord.lteq(root(t), root(tq)) then
(t, ts)
else
(tq, t :: tsq)
val (Node(_, _, c), tsq) = getMin(t, ts)
meld(c.reverse, tsq)
}
trait Bogus1BinomialHeap extends BinomialHeap {
override def findMin(ts: H) = ts match
case Nil => throw new NoSuchElementException("min of empty heap")
case t :: ts => root(t)
}
trait Bogus2BinomialHeap extends BinomialHeap {
override protected def link(t1: Node, t2: Node): Node = // t1.r == t2.r
if !ord.lteq(t1.x, t2.x) then
Node(t1.x, t1.r + 1, t2 :: t1.c)
else
Node(t2.x, t2.r + 1, t1 :: t2.c)
}
trait Bogus3BinomialHeap extends BinomialHeap {
override protected def link(t1: Node, t2: Node): Node = // t1.r == t2.r
if ord.lteq(t1.x, t2.x) then
Node(t1.x, t1.r + 1, t1 :: t1.c)
else
Node(t2.x, t2.r + 1, t2 :: t2.c)
}
trait Bogus4BinomialHeap extends BinomialHeap {
override def deleteMin(ts: H) = ts match
case Nil => throw new NoSuchElementException("delete min of empty heap")
case t :: ts => meld(t.c.reverse, ts)
}
trait Bogus5BinomialHeap extends BinomialHeap {
override def meld(ts1: H, ts2: H) = ts1 match
case Nil => ts2
case t1 :: ts1 => List(Node(t1.x, t1.r, ts1++ts2))
}