Compare commits
No commits in common. "forcomp" and "codecs" have entirely different histories.
@ -7,7 +7,9 @@ stages:
|
||||
|
||||
compile:
|
||||
stage: build
|
||||
image: lampepfl/moocs-dotty:2019-09-17-2
|
||||
image: lampepfl/moocs-dotty:2019-10-16
|
||||
except:
|
||||
- tags
|
||||
tags:
|
||||
- cs210
|
||||
script:
|
||||
@ -19,10 +21,12 @@ compile:
|
||||
|
||||
grade:
|
||||
stage: grade
|
||||
except:
|
||||
- tags
|
||||
tags:
|
||||
- cs210
|
||||
image:
|
||||
name: registry.gitlab.com/fnux/cs210-grading-images/progfun1-patmat:20191016-626d0012efc94653bff8736b2570386000f65ea2
|
||||
name: registry.gitlab.com/fnux/cs210-grading-images/progfun2-codecs:20191027-dfbea8aed96096ed3af1cf1958549b97328d4c25
|
||||
entrypoint: [""]
|
||||
allow_failure: true
|
||||
before_script:
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
# CS-210: For-comprehensions and Collections
|
||||
|
||||
# CS-210: Codecs
|
||||
|
||||
Please follow the [instructions from the main course
|
||||
respository](https://gitlab.epfl.ch/lamp/cs-210-functional-programming-2019/blob/master/week5/00-homework5.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).
|
||||
|
||||
20
build.sbt
20
build.sbt
@ -1,12 +1,16 @@
|
||||
course := "progfun1"
|
||||
assignment := "forcomp"
|
||||
course := "progfun2"
|
||||
assignment := "codecs"
|
||||
name := course.value + "-" + assignment.value
|
||||
testSuite := "forcomp.AnagramsSuite"
|
||||
testSuite := "codecs.CodecsSuite"
|
||||
|
||||
scalaVersion := "0.19.0-bin-20190918-dd68eb8-NIGHTLY"
|
||||
|
||||
scalacOptions ++= Seq("-language:implicitConversions", "-deprecation")
|
||||
|
||||
libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % Test
|
||||
scalaVersion := "0.19.0-RC1"
|
||||
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.
@ -18,6 +18,8 @@ object MOOCSettings extends AutoPlugin {
|
||||
override def trigger = allRequirements
|
||||
|
||||
override val projectSettings: Seq[Def.Setting[_]] = Seq(
|
||||
parallelExecution in Test := false
|
||||
parallelExecution in Test := false,
|
||||
// Report test result after each test instead of waiting for every test to finish
|
||||
logBuffered in Test := false
|
||||
)
|
||||
}
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % Test
|
||||
// Used for base64 encoding
|
||||
libraryDependencies += "commons-codec" % "commons-codec" % "1.10"
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
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,174 +0,0 @@
|
||||
package forcomp
|
||||
|
||||
object Anagrams extends AnagramsInterface {
|
||||
|
||||
/** A word is simply a `String`. */
|
||||
type Word = String
|
||||
|
||||
/** A sentence is a `List` of words. */
|
||||
type Sentence = List[Word]
|
||||
|
||||
/** `Occurrences` is a `List` of pairs of characters and positive integers saying
|
||||
* how often the character appears.
|
||||
* This list is sorted alphabetically w.r.t. to the character in each pair.
|
||||
* All characters in the occurrence list are lowercase.
|
||||
*
|
||||
* Any list of pairs of lowercase characters and their frequency which is not sorted
|
||||
* is **not** an occurrence list.
|
||||
*
|
||||
* Note: If the frequency of some character is zero, then that character should not be
|
||||
* in the list.
|
||||
*/
|
||||
type Occurrences = List[(Char, Int)]
|
||||
|
||||
/** The dictionary is simply a sequence of words.
|
||||
* It is predefined and obtained as a sequence using the utility method `loadDictionary`.
|
||||
*/
|
||||
val dictionary: List[Word] = Dictionary.loadDictionary
|
||||
|
||||
/** Converts the word into its character occurrence list.
|
||||
*
|
||||
* Note: the uppercase and lowercase version of the character are treated as the
|
||||
* same character, and are represented as a lowercase character in the occurrence list.
|
||||
*
|
||||
* Note: you must use `groupBy` to implement this method!
|
||||
*/
|
||||
def wordOccurrences(w: Word): Occurrences = w.toLowerCase.toSeq.groupBy(e => e).view.mapValues(t => t.length).toList.sorted
|
||||
|
||||
/** Converts a sentence into its character occurrence list. */
|
||||
def sentenceOccurrences(s: Sentence): Occurrences = wordOccurrences(s.mkString)
|
||||
|
||||
/** The `dictionaryByOccurrences` is a `Map` from different occurrences to a sequence of all
|
||||
* the words that have that occurrence count.
|
||||
* This map serves as an easy way to obtain all the anagrams of a word given its occurrence list.
|
||||
*
|
||||
* For example, the word "eat" has the following character occurrence list:
|
||||
*
|
||||
* `List(('a', 1), ('e', 1), ('t', 1))`
|
||||
*
|
||||
* Incidentally, so do the words "ate" and "tea".
|
||||
*
|
||||
* This means that the `dictionaryByOccurrences` map will contain an entry:
|
||||
*
|
||||
* List(('a', 1), ('e', 1), ('t', 1)) -> Seq("ate", "eat", "tea")
|
||||
*
|
||||
*/
|
||||
lazy val dictionaryByOccurrences: Map[Occurrences, List[Word]] = dictionary.groupBy(wordOccurrences)
|
||||
|
||||
/** Returns all the anagrams of a given word. */
|
||||
def wordAnagrams(word: Word): List[Word] = dictionaryByOccurrences(wordOccurrences(word))
|
||||
|
||||
// val o : List[Occurrences] = occurrences.map( x => (for(i <- 1 until (x._2+1)) yield (x._1,i)).toList)
|
||||
// o.foldRight(List[Occurrences](Nil))((x,y) => y ++ (for(i <- x; j <- y) yield (i :: j)))
|
||||
/** Returns the list of all subsets of the occurrence list.
|
||||
* This includes the occurrence itself, i.e. `List(('k', 1), ('o', 1))`
|
||||
* is a subset of `List(('k', 1), ('o', 1))`.
|
||||
* It also include the empty subset `List()`.
|
||||
*
|
||||
* Example: the subsets of the occurrence list `List(('a', 2), ('b', 2))` are:
|
||||
*
|
||||
* List(
|
||||
* List(),
|
||||
* List(('a', 1)),
|
||||
* List(('a', 2)),
|
||||
* List(('b', 1)),
|
||||
* List(('a', 1), ('b', 1)),
|
||||
* List(('a', 2), ('b', 1)),
|
||||
* List(('b', 2)),
|
||||
* List(('a', 1), ('b', 2)),
|
||||
* List(('a', 2), ('b', 2))
|
||||
* )
|
||||
*
|
||||
* Note that the order of the occurrence list subsets does not matter -- the subsets
|
||||
* in the example above could have been displayed in some other order.
|
||||
*/
|
||||
def combinations(occurrences: Occurrences): List[Occurrences] =
|
||||
occurrences.map( x => (for(i <- 1 until (x._2+1)) yield (x._1,i)).toList)
|
||||
.foldRight(List[Occurrences](Nil))((x,y) =>
|
||||
y ::: (for(i <- x; j <- y) yield (i :: j)))
|
||||
|
||||
/** Subtracts occurrence list `y` from occurrence list `x`.
|
||||
*
|
||||
* The precondition is that the occurrence list `y` is a subset of
|
||||
* the occurrence list `x` -- any character appearing in `y` must
|
||||
* appear in `x`, and its frequency in `y` must be smaller or equal
|
||||
* than its frequency in `x`.
|
||||
*
|
||||
* Note: the resulting value is an occurrence - meaning it is sorted
|
||||
* and has no zero-entries.
|
||||
*/
|
||||
def subtract(x: Occurrences, y: Occurrences): Occurrences =
|
||||
y.foldLeft(Map(x: _*))((map, pair) => {
|
||||
map.updated(pair._1, map.apply(pair._1) - pair._2)
|
||||
}).filter(e => e._2 !=0 ).toList.sorted
|
||||
|
||||
/** Returns a list of all anagram sentences of the given sentence.
|
||||
*
|
||||
* An anagram of a sentence is formed by taking the occurrences of all the characters of
|
||||
* all the words in the sentence, and producing all possible combinations of words with those characters,
|
||||
* such that the words have to be from the dictionary.
|
||||
*
|
||||
* The number of words in the sentence and its anagrams does not have to correspond.
|
||||
* For example, the sentence `List("I", "love", "you")` is an anagram of the sentence `List("You", "olive")`.
|
||||
*
|
||||
* Also, two sentences with the same words but in a different order are considered two different anagrams.
|
||||
* For example, sentences `List("You", "olive")` and `List("olive", "you")` are different anagrams of
|
||||
* `List("I", "love", "you")`.
|
||||
*
|
||||
* Here is a full example of a sentence `List("Yes", "man")` and its anagrams for our dictionary:
|
||||
*
|
||||
* List(
|
||||
* List(en, as, my),
|
||||
* List(en, my, as),
|
||||
* List(man, yes),
|
||||
* List(men, say),
|
||||
* List(as, en, my),
|
||||
* List(as, my, en),
|
||||
* List(sane, my),
|
||||
* List(Sean, my),
|
||||
* List(my, en, as),
|
||||
* List(my, as, en),
|
||||
* List(my, sane),
|
||||
* List(my, Sean),
|
||||
* List(say, men),
|
||||
* List(yes, man)
|
||||
* )
|
||||
*
|
||||
* The different sentences do not have to be output in the order shown above - any order is fine as long as
|
||||
* all the anagrams are there. Every returned word has to exist in the dictionary.
|
||||
*
|
||||
* Note: in case that the words of the sentence are in the dictionary, then the sentence is the anagram of itself,
|
||||
* so it has to be returned in this list.
|
||||
*
|
||||
* Note: There is only one anagram of an empty sentence.
|
||||
*/
|
||||
def sentenceAnagrams(sentence: Sentence): List[Sentence] = {
|
||||
def iter(occurrences: Occurrences): List[Sentence] = {
|
||||
if (occurrences.isEmpty) List(Nil)
|
||||
else for {
|
||||
combination <- combinations( occurrences )
|
||||
word <- dictionaryByOccurrences getOrElse (combination, Nil)
|
||||
sentence <- iter( subtract(occurrences,wordOccurrences(word)) )
|
||||
if !combination.isEmpty
|
||||
} yield word :: sentence
|
||||
}
|
||||
|
||||
iter( sentenceOccurrences(sentence) )
|
||||
}
|
||||
}
|
||||
|
||||
object Dictionary {
|
||||
def loadDictionary: List[String] =
|
||||
val wordstream = Option {
|
||||
getClass.getResourceAsStream(List("forcomp", "linuxwords.txt").mkString("/", "/", ""))
|
||||
} getOrElse(sys.error("Could not load word list, dictionary file not found"))
|
||||
try
|
||||
val s = scala.io.Source.fromInputStream(wordstream)
|
||||
s.getLines.toList
|
||||
catch
|
||||
case e: Exception =>
|
||||
println("Could not load word list: " + e)
|
||||
throw e
|
||||
finally
|
||||
wordstream.close()
|
||||
}
|
||||
@ -1,15 +0,0 @@
|
||||
package forcomp
|
||||
|
||||
/**
|
||||
* The interface used by the grading infrastructure. Do not change signatures
|
||||
* or your submission will fail with a NoSuchMethodError.
|
||||
*/
|
||||
trait AnagramsInterface {
|
||||
def wordOccurrences(w: String): List[(Char, Int)]
|
||||
def sentenceOccurrences(s: List[String]): List[(Char, Int)]
|
||||
def dictionaryByOccurrences: Map[List[(Char, Int)], List[String]]
|
||||
def wordAnagrams(word: String): List[String]
|
||||
def combinations(occurrences: List[(Char, Int)]): List[List[(Char, Int)]]
|
||||
def subtract(x: List[(Char, Int)], y: List[(Char, Int)]): List[(Char, Int)]
|
||||
def sentenceAnagrams(sentence: List[String]): List[List[String]]
|
||||
}
|
||||
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,91 +0,0 @@
|
||||
package forcomp
|
||||
|
||||
import org.junit._
|
||||
import org.junit.Assert.assertEquals
|
||||
|
||||
|
||||
class AnagramsSuite {
|
||||
import Anagrams._
|
||||
|
||||
@Test def `wordOccurrences: abcd (3pts)`: Unit =
|
||||
assertEquals(List(('a', 1), ('b', 1), ('c', 1), ('d', 1)), wordOccurrences("abcd"))
|
||||
|
||||
@Test def `wordOccurrences: Robert (3pts)`: Unit =
|
||||
assertEquals(List(('b', 1), ('e', 1), ('o', 1), ('r', 2), ('t', 1)), wordOccurrences("Robert"))
|
||||
|
||||
|
||||
@Test def `sentenceOccurrences: abcd e (5pts)`: Unit =
|
||||
assertEquals(List(('a', 1), ('b', 1), ('c', 1), ('d', 1), ('e', 1)), sentenceOccurrences(List("abcd", "e")))
|
||||
|
||||
|
||||
@Test def `dictionaryByOccurrences.get: eat (10pts)`: Unit =
|
||||
assertEquals(Some(Set("ate", "eat", "tea")), dictionaryByOccurrences.get(List(('a', 1), ('e', 1), ('t', 1))).map(_.toSet))
|
||||
|
||||
|
||||
@Test def `wordAnagrams married (2pts)`: Unit =
|
||||
assertEquals(Set("married", "admirer"), wordAnagrams("married").toSet)
|
||||
|
||||
@Test def `wordAnagrams player (2pts)`: Unit =
|
||||
assertEquals(Set("parley", "pearly", "player", "replay"), wordAnagrams("player").toSet)
|
||||
|
||||
|
||||
|
||||
@Test def `subtract: lard - r (10pts)`: Unit =
|
||||
val lard = List(('a', 1), ('d', 1), ('l', 1), ('r', 1))
|
||||
val r = List(('r', 1))
|
||||
val lad = List(('a', 1), ('d', 1), ('l', 1))
|
||||
assertEquals(lad, subtract(lard, r))
|
||||
|
||||
|
||||
@Test def `combinations: [] (8pts)`: Unit =
|
||||
assertEquals(List(Nil), combinations(Nil))
|
||||
|
||||
@Test def `combinations: abba (8pts)`: Unit =
|
||||
val abba = List(('a', 2), ('b', 2))
|
||||
val abbacomb = List(
|
||||
List(),
|
||||
List(('a', 1)),
|
||||
List(('a', 2)),
|
||||
List(('b', 1)),
|
||||
List(('a', 1), ('b', 1)),
|
||||
List(('a', 2), ('b', 1)),
|
||||
List(('b', 2)),
|
||||
List(('a', 1), ('b', 2)),
|
||||
List(('a', 2), ('b', 2))
|
||||
)
|
||||
assertEquals(abbacomb.toSet, combinations(abba).toSet)
|
||||
|
||||
|
||||
@Test def `sentence anagrams: [] (10pts)`: Unit =
|
||||
val sentence = List()
|
||||
assertEquals(List(Nil), sentenceAnagrams(sentence))
|
||||
|
||||
@Test def `sentence anagrams: Linux rulez (10pts)`: Unit =
|
||||
val sentence = List("Linux", "rulez")
|
||||
val anas = List(
|
||||
List("Rex", "Lin", "Zulu"),
|
||||
List("nil", "Zulu", "Rex"),
|
||||
List("Rex", "nil", "Zulu"),
|
||||
List("Zulu", "Rex", "Lin"),
|
||||
List("null", "Uzi", "Rex"),
|
||||
List("Rex", "Zulu", "Lin"),
|
||||
List("Uzi", "null", "Rex"),
|
||||
List("Rex", "null", "Uzi"),
|
||||
List("null", "Rex", "Uzi"),
|
||||
List("Lin", "Rex", "Zulu"),
|
||||
List("nil", "Rex", "Zulu"),
|
||||
List("Rex", "Uzi", "null"),
|
||||
List("Rex", "Zulu", "nil"),
|
||||
List("Zulu", "Rex", "nil"),
|
||||
List("Zulu", "Lin", "Rex"),
|
||||
List("Lin", "Zulu", "Rex"),
|
||||
List("Uzi", "Rex", "null"),
|
||||
List("Zulu", "nil", "Rex"),
|
||||
List("rulez", "Linux"),
|
||||
List("Linux", "rulez")
|
||||
)
|
||||
assertEquals(anas.toSet, sentenceAnagrams(sentence).toSet)
|
||||
|
||||
|
||||
@Rule def individualTestTimeout = new org.junit.rules.Timeout(10 * 1000)
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user