Compare commits
No commits in common. "streams" and "codecs" have entirely different histories.
@ -26,7 +26,7 @@ grade:
|
||||
tags:
|
||||
- cs210
|
||||
image:
|
||||
name: registry.gitlab.com/fnux/cs210-grading-images/progfun2-streams:20191030-43a7371aecb1bee74b8e4c3b0aba175f3ff4d0c6
|
||||
name: registry.gitlab.com/fnux/cs210-grading-images/progfun2-codecs:20191027-dfbea8aed96096ed3af1cf1958549b97328d4c25
|
||||
entrypoint: [""]
|
||||
allow_failure: true
|
||||
before_script:
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
# CS-210: Streams (Bloxorz)
|
||||
|
||||
# CS-210: Codecs
|
||||
|
||||
Please follow the [instructions from the main course
|
||||
respository](https://gitlab.epfl.ch/lamp/cs-210-functional-programming-2019/blob/master/week9/00-homework7.md).
|
||||
respository](https://gitlab.epfl.ch/lamp/cs-210-functional-programming-2019/blob/master/week11/00-homework8.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).
|
||||
|
||||
16
build.sbt
16
build.sbt
@ -1,12 +1,16 @@
|
||||
course := "progfun2"
|
||||
assignment := "streams"
|
||||
assignment := "codecs"
|
||||
name := course.value + "-" + assignment.value
|
||||
testSuite := "streams.BloxorzSuite"
|
||||
testSuite := "codecs.CodecsSuite"
|
||||
|
||||
scalaVersion := "0.19.0-RC1"
|
||||
|
||||
scalacOptions ++= Seq("-language:implicitConversions", "-deprecation")
|
||||
libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % Test
|
||||
libraryDependencies += ("org.scalacheck" %% "scalacheck" % "1.14.2").withDottyCompat(scalaVersion.value)
|
||||
scalacOptions ++= Seq("-deprecation")
|
||||
libraryDependencies ++= Seq(
|
||||
("org.scalacheck" %% "scalacheck" % "1.14.2" % Test).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")
|
||||
|
||||
initialCommands in console := """import codecs.{_, given}"""
|
||||
|
||||
Binary file not shown.
283
src/main/scala/codecs/codecs.scala
Normal file
283
src/main/scala/codecs/codecs.scala
Normal file
@ -0,0 +1,283 @@
|
||||
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)))
|
||||
}
|
||||
|
||||
}
|
||||
74
src/main/scala/codecs/json.scala
Normal file
74
src/main/scala/codecs/json.scala
Normal file
@ -0,0 +1,74 @@
|
||||
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)
|
||||
}
|
||||
@ -1,49 +0,0 @@
|
||||
package streams
|
||||
|
||||
/**
|
||||
* A main object that can be used to execute the Bloxorz solver
|
||||
*/
|
||||
object Bloxorz extends App {
|
||||
|
||||
/**
|
||||
* A level constructed using the `InfiniteTerrain` trait which defines
|
||||
* the terrain to be valid at every position.
|
||||
*/
|
||||
object InfiniteLevel extends Solver with InfiniteTerrain {
|
||||
val startPos = Pos(1,3)
|
||||
val goal = Pos(5,8)
|
||||
}
|
||||
|
||||
println(InfiniteLevel.solution)
|
||||
|
||||
/**
|
||||
* A simple level constructed using the StringParserTerrain
|
||||
*/
|
||||
abstract class Level extends Solver with StringParserTerrain
|
||||
|
||||
object Level0 extends Level {
|
||||
val level =
|
||||
"""------
|
||||
|--ST--
|
||||
|--oo--
|
||||
|--oo--
|
||||
|------""".stripMargin
|
||||
}
|
||||
|
||||
println(Level0.solution)
|
||||
|
||||
/**
|
||||
* Level 1 of the official Bloxorz game
|
||||
*/
|
||||
object Level1 extends Level {
|
||||
val level =
|
||||
"""ooo-------
|
||||
|oSoooo----
|
||||
|ooooooooo-
|
||||
|-ooooooooo
|
||||
|-----ooToo
|
||||
|------ooo-""".stripMargin
|
||||
}
|
||||
|
||||
println(Level1.solution)
|
||||
}
|
||||
@ -1,170 +0,0 @@
|
||||
package streams
|
||||
|
||||
/**
|
||||
* This trait represents the layout and building blocks of the game
|
||||
*/
|
||||
trait GameDef {
|
||||
|
||||
/**
|
||||
* The case class `Pos` encodes positions in the terrain.
|
||||
*
|
||||
* IMPORTANT NOTE
|
||||
* - The `row` coordinate denotes the position on the vertical axis
|
||||
* - The `col` coordinate is used for the horizontal axis
|
||||
* - The coordinates increase when moving down and right
|
||||
*
|
||||
* Illustration:
|
||||
*
|
||||
* 0 1 2 3 <- col axis
|
||||
* 0 o o o o
|
||||
* 1 o o o o
|
||||
* 2 o # o o # is at position Pos(2, 1)
|
||||
* 3 o o o o
|
||||
*
|
||||
* ^
|
||||
* |
|
||||
*
|
||||
* row axis
|
||||
*/
|
||||
case class Pos(row: Int, col: Int) {
|
||||
/** The position obtained by changing the `row` coordinate by `d` */
|
||||
def deltaRow(d: Int): Pos = copy(row = row + d)
|
||||
|
||||
/** The position obtained by changing the `col` coordinate by `d` */
|
||||
def deltaCol(d: Int): Pos = copy(col = col + d)
|
||||
}
|
||||
|
||||
/**
|
||||
* The position where the block is located initially.
|
||||
*
|
||||
* This value is left abstract, it will be defined in concrete
|
||||
* instances of the game.
|
||||
*/
|
||||
def startPos: Pos
|
||||
|
||||
/**
|
||||
* The target position where the block has to go.
|
||||
* This value is left abstract.
|
||||
*/
|
||||
def goal: Pos
|
||||
|
||||
/**
|
||||
* The terrain is represented as a function from positions to
|
||||
* booleans. The function returns `true` for every position that
|
||||
* is inside the terrain.
|
||||
*
|
||||
* As explained in the documentation of class `Pos`, the `row` axis
|
||||
* is the vertical one and increases from top to bottom.
|
||||
*/
|
||||
type Terrain = Pos => Boolean
|
||||
|
||||
|
||||
/**
|
||||
* The terrain of this game. This value is left abstract.
|
||||
*/
|
||||
def terrain: Terrain
|
||||
|
||||
|
||||
/**
|
||||
* In Bloxorz, we can move left, right, Up or down.
|
||||
* These moves are encoded as case objects.
|
||||
*/
|
||||
sealed abstract class Move
|
||||
case object Left extends Move
|
||||
case object Right extends Move
|
||||
case object Up extends Move
|
||||
case object Down extends Move
|
||||
|
||||
/**
|
||||
* This function returns the block at the start position of
|
||||
* the game.
|
||||
*/
|
||||
def startBlock: Block = Block(startPos, startPos)
|
||||
|
||||
|
||||
/**
|
||||
* A block is represented by the position of the two cubes that
|
||||
* it consists of. We make sure that `b1` is lexicographically
|
||||
* smaller than `b2`.
|
||||
*/
|
||||
case class Block(b1: Pos, b2: Pos) {
|
||||
|
||||
// checks the requirement mentioned above
|
||||
require(b1.row <= b2.row && b1.col <= b2.col, s"Invalid block position: b1=$b1, b2=$b2")
|
||||
|
||||
/**
|
||||
* Returns a block where the `row` coordinates of `b1` and `b2` are
|
||||
* changed by `d1` and `d2`, respectively.
|
||||
*/
|
||||
def deltaRow(d1: Int, d2: Int) = Block(b1.deltaRow(d1), b2.deltaRow(d2))
|
||||
|
||||
/**
|
||||
* Returns a block where the `col` coordinates of `b1` and `b2` are
|
||||
* changed by `d1` and `d2`, respectively.
|
||||
*/
|
||||
def deltaCol(d1: Int, d2: Int) = Block(b1.deltaCol(d1), b2.deltaCol(d2))
|
||||
|
||||
|
||||
/** The block obtained by moving left */
|
||||
def left =
|
||||
if isStanding then
|
||||
deltaCol(-2, -1)
|
||||
else if b1.row == b2.row then
|
||||
deltaCol(-1, -2)
|
||||
else
|
||||
deltaCol(-1, -1)
|
||||
|
||||
/** The block obtained by moving right */
|
||||
def right =
|
||||
if isStanding then
|
||||
deltaCol(1, 2)
|
||||
else if b1.row == b2.row then
|
||||
deltaCol(2, 1)
|
||||
else
|
||||
deltaCol(1, 1)
|
||||
|
||||
/** The block obtained by moving up */
|
||||
def up =
|
||||
if isStanding then
|
||||
deltaRow(-2, -1)
|
||||
else if b1.row == b2.row then
|
||||
deltaRow(-1, -1)
|
||||
else
|
||||
deltaRow(-1, -2)
|
||||
|
||||
/** The block obtained by moving down */
|
||||
def down =
|
||||
if isStanding then
|
||||
deltaRow(1, 2)
|
||||
else if b1.row == b2.row then
|
||||
deltaRow(1, 1)
|
||||
else
|
||||
deltaRow(2, 1)
|
||||
|
||||
|
||||
/**
|
||||
* Returns the list of blocks that can be obtained by moving
|
||||
* the current block, together with the corresponding move.
|
||||
*/
|
||||
def neighbors: List[(Block, Move)] =
|
||||
List((left, Left), (right, Right), (up, Up), (down, Down))
|
||||
|
||||
/**
|
||||
* Returns the list of positions reachable from the current block
|
||||
* which are inside the terrain.
|
||||
*/
|
||||
def legalNeighbors: List[(Block, Move)] = neighbors.filter{
|
||||
case (b, _) => b.isLegal
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` if the block is standing.
|
||||
*/
|
||||
def isStanding: Boolean = b1 == b2
|
||||
|
||||
/**
|
||||
* Returns `true` if the block is entirely inside the terrain.
|
||||
*/
|
||||
def isLegal: Boolean = terrain(b1) && terrain(b2)
|
||||
}
|
||||
}
|
||||
@ -1,15 +0,0 @@
|
||||
package streams
|
||||
|
||||
/**
|
||||
* This trait defines an infinite terrain, where the block can
|
||||
* go on any position.
|
||||
*
|
||||
* It keeps the `startPos` and the `goal` positions abstract.
|
||||
*
|
||||
* Using this trait is useful for testing. It can be used to find
|
||||
* the shortest path between two positions without terrain
|
||||
* restrictions.
|
||||
*/
|
||||
trait InfiniteTerrain extends GameDef {
|
||||
val terrain: Terrain = (pos: Pos) => true
|
||||
}
|
||||
@ -1,103 +0,0 @@
|
||||
package streams
|
||||
|
||||
/**
|
||||
* This component implements the solver for the Bloxorz game
|
||||
*/
|
||||
trait Solver extends GameDef {
|
||||
|
||||
/**
|
||||
* Returns `true` if the block `b` is at the final position
|
||||
*/
|
||||
def done(b: Block): Boolean = b.b1 == goal && b.isStanding
|
||||
|
||||
/**
|
||||
* This function takes two arguments: the current block `b` and
|
||||
* a list of moves `history` that was required to reach the
|
||||
* position of `b`.
|
||||
*
|
||||
* The `head` element of the `history` list is the latest move
|
||||
* that was executed, i.e. the last move that was performed for
|
||||
* the block to end up at position `b`.
|
||||
*
|
||||
* The function returns a lazy list of pairs: the first element of
|
||||
* the each pair is a neighboring block, and the second element
|
||||
* is the augmented history of moves required to reach this block.
|
||||
*
|
||||
* It should only return valid neighbors, i.e. block positions
|
||||
* that are inside the terrain.
|
||||
*/
|
||||
def neighborsWithHistory(b: Block, history: List[Move]): LazyList[(Block, List[Move])] = {
|
||||
lazy val result = b.legalNeighbors.map({pair=> (pair._1, pair._2 +: history)})
|
||||
result.to(LazyList)
|
||||
}
|
||||
|
||||
/**
|
||||
* This function returns the list of neighbors without the block
|
||||
* positions that have already been explored. We will use it to
|
||||
* make sure that we don't explore circular paths.
|
||||
*/
|
||||
def newNeighborsOnly(neighbors: LazyList[(Block, List[Move])],
|
||||
explored: Set[Block]): LazyList[(Block, List[Move])] = {
|
||||
neighbors.filter(n => !explored.contains(n._1))
|
||||
}
|
||||
|
||||
/**
|
||||
* The function `from` returns the lazy list of all possible paths
|
||||
* that can be followed, starting at the `head` of the `initial`
|
||||
* lazy list.
|
||||
*
|
||||
* The blocks in the lazy list `initial` are sorted by ascending path
|
||||
* length: the block positions with the shortest paths (length of
|
||||
* move list) are at the head of the lazy list.
|
||||
*
|
||||
* The parameter `explored` is a set of block positions that have
|
||||
* been visited before, on the path to any of the blocks in the
|
||||
* lazy list `initial`. When search reaches a block that has already
|
||||
* been explored before, that position should not be included a
|
||||
* second time to avoid cycles.
|
||||
*
|
||||
* The resulting lazy list should be sorted by ascending path length,
|
||||
* i.e. the block positions that can be reached with the fewest
|
||||
* amount of moves should appear first in the lazy list.
|
||||
*
|
||||
* Note: the solution should not look at or compare the lengths
|
||||
* of different paths - the implementation should naturally
|
||||
* construct the correctly sorted lazy list.
|
||||
*/
|
||||
def from(initial: LazyList[(Block, List[Move])],
|
||||
explored: Set[Block]): LazyList[(Block, List[Move])] = {
|
||||
if (initial.isEmpty) LazyList.empty
|
||||
else {
|
||||
val more = for {
|
||||
pair <- initial
|
||||
next <- newNeighborsOnly (neighborsWithHistory(pair._1, pair._2), explored)
|
||||
} yield next
|
||||
initial #::: from(more, explored ++ (more.map(_._1)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The lazy list of all paths that begin at the starting block.
|
||||
*/
|
||||
lazy val pathsFromStart: LazyList[(Block, List[Move])] = from(neighborsWithHistory(startBlock, List[Move]()), Set(startBlock))
|
||||
|
||||
/**
|
||||
* Returns a lazy list of all possible pairs of the goal block along
|
||||
* with the history how it was reached.
|
||||
*/
|
||||
lazy val pathsToGoal: LazyList[(Block, List[Move])] = pathsFromStart.filter({case (b, m) => done(b)})
|
||||
|
||||
/**
|
||||
* The (or one of the) shortest sequence(s) of moves to reach the
|
||||
* goal. If the goal cannot be reached, the empty list is returned.
|
||||
*
|
||||
* Note: the `head` element of the returned list should represent
|
||||
* the first move that the player should perform from the starting
|
||||
* position.
|
||||
*/
|
||||
lazy val solution: List[Move] = pathsToGoal.headOption match {
|
||||
case None => List.empty
|
||||
case Some(pair) => (pair._2).reverse
|
||||
}
|
||||
}
|
||||
@ -1,83 +0,0 @@
|
||||
package streams
|
||||
|
||||
/**
|
||||
* This component implements a parser to define terrains from a
|
||||
* graphical ASCII representation.
|
||||
*
|
||||
* When mixing in that component, a level can be defined by
|
||||
* defining the field `level` in the following form:
|
||||
*
|
||||
* val level =
|
||||
* """------
|
||||
* |--ST--
|
||||
* |--oo--
|
||||
* |--oo--
|
||||
* |------""".stripMargin
|
||||
*
|
||||
* - The `-` character denotes parts which are outside the terrain
|
||||
* - `o` denotes fields which are part of the terrain
|
||||
* - `S` denotes the start position of the block (which is also considered
|
||||
inside the terrain)
|
||||
* - `T` denotes the final position of the block (which is also considered
|
||||
inside the terrain)
|
||||
*
|
||||
* In this example, the first and last lines could be omitted, and
|
||||
* also the columns that consist of `-` characters only.
|
||||
*/
|
||||
trait StringParserTerrain extends GameDef {
|
||||
|
||||
/**
|
||||
* A ASCII representation of the terrain. This field should remain
|
||||
* abstract here.
|
||||
*/
|
||||
val level: String
|
||||
|
||||
/**
|
||||
* This method returns terrain function that represents the terrain
|
||||
* in `levelVector`. The vector contains parsed version of the `level`
|
||||
* string. For example, the following level
|
||||
*
|
||||
* val level =
|
||||
* """ST
|
||||
* |oo
|
||||
* |oo""".stripMargin
|
||||
*
|
||||
* is represented as
|
||||
*
|
||||
* Vector(Vector('S', 'T'), Vector('o', 'o'), Vector('o', 'o'))
|
||||
*
|
||||
* The resulting function should return `true` if the position `pos` is
|
||||
* a valid position (not a '-' character) inside the terrain described
|
||||
* by `levelVector`.
|
||||
*/
|
||||
def terrainFunction(levelVector: Vector[Vector[Char]]): Pos => Boolean = {
|
||||
case Pos(x,y) => (for{
|
||||
row <- levelVector.lift(x)
|
||||
ch <- row.lift(y)
|
||||
if(ch != '-')
|
||||
} yield ch).isDefined
|
||||
}
|
||||
|
||||
/**
|
||||
* This function should return the position of character `c` in the
|
||||
* terrain described by `levelVector`. You can assume that the `c`
|
||||
* appears exactly once in the terrain.
|
||||
*
|
||||
* Hint: you can use the functions `indexWhere` and / or `indexOf` of the
|
||||
* `Vector` class
|
||||
*/
|
||||
def findChar(c: Char, levelVector: Vector[Vector[Char]]): Pos = {
|
||||
val ys = levelVector.map(_.indexOf(c))
|
||||
val x = ys.indexWhere(_ >= 0)
|
||||
|
||||
Pos(x, ys(x))
|
||||
}
|
||||
|
||||
private lazy val vector: Vector[Vector[Char]] =
|
||||
Vector(level.split("\r?\n").map(str => Vector(str: _*)).toIndexedSeq: _*)
|
||||
|
||||
lazy val terrain: Terrain = terrainFunction(vector)
|
||||
lazy val startPos: Pos = findChar('S', vector)
|
||||
lazy val goal: Pos = findChar('T', vector)
|
||||
|
||||
}
|
||||
115
src/test/scala/codecs/CodecsSuite.scala
Normal file
115
src/test/scala/codecs/CodecsSuite.scala
Normal file
@ -0,0 +1,115 @@
|
||||
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}]")
|
||||
|
||||
}
|
||||
@ -1,74 +0,0 @@
|
||||
package streams
|
||||
|
||||
import org.junit._
|
||||
import org.junit.Assert.assertEquals
|
||||
|
||||
import Bloxorz._
|
||||
|
||||
class BloxorzSuite {
|
||||
trait SolutionChecker extends GameDef with Solver with StringParserTerrain {
|
||||
/**
|
||||
* This method applies a list of moves `ls` to the block at position
|
||||
* `startPos`. This can be used to verify if a certain list of moves
|
||||
* is a valid solution, i.e. leads to the goal.
|
||||
*/
|
||||
def solve(ls: List[Move]): Block =
|
||||
ls.foldLeft(startBlock) { case (block, move) =>
|
||||
require(block.isLegal) // The solution must always lead to legal blocks
|
||||
move match
|
||||
case Left => block.left
|
||||
case Right => block.right
|
||||
case Up => block.up
|
||||
case Down => block.down
|
||||
}
|
||||
}
|
||||
|
||||
trait Level1 extends SolutionChecker {
|
||||
/* terrain for level 1*/
|
||||
|
||||
val level =
|
||||
"""ooo-------
|
||||
|oSoooo----
|
||||
|ooooooooo-
|
||||
|-ooooooooo
|
||||
|-----ooToo
|
||||
|------ooo-""".stripMargin
|
||||
|
||||
val optsolution = List(Right, Right, Down, Right, Right, Right, Down)
|
||||
}
|
||||
|
||||
|
||||
@Test def `terrain function level 1 (10pts)`: Unit =
|
||||
new Level1 {
|
||||
assert(terrain(Pos(0,0)), "0,0")
|
||||
assert(terrain(Pos(1,1)), "1,1") // start
|
||||
assert(terrain(Pos(4,7)), "4,7") // goal
|
||||
assert(terrain(Pos(5,8)), "5,8")
|
||||
assert(!terrain(Pos(5,9)), "5,9")
|
||||
assert(terrain(Pos(4,9)), "4,9")
|
||||
assert(!terrain(Pos(6,8)), "6,8")
|
||||
assert(!terrain(Pos(4,11)), "4,11")
|
||||
assert(!terrain(Pos(-1,0)), "-1,0")
|
||||
assert(!terrain(Pos(0,-1)), "0,-1")
|
||||
}
|
||||
|
||||
@Test def `find char level 1 (10pts)`: Unit =
|
||||
new Level1 {
|
||||
assertEquals(Pos(1, 1), startPos)
|
||||
}
|
||||
|
||||
|
||||
@Test def `optimal solution for level 1 (5pts)`: Unit =
|
||||
new Level1 {
|
||||
assertEquals(Block(goal, goal), solve(solution))
|
||||
}
|
||||
|
||||
|
||||
@Test def `optimal solution length for level 1 (5pts)`: Unit =
|
||||
new Level1 {
|
||||
assertEquals(optsolution.length, solution.length)
|
||||
}
|
||||
|
||||
|
||||
@Rule def individualTestTimeout = new org.junit.rules.Timeout(10 * 1000)
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user