Skip to content
Snippets Groups Projects
Commit 9d774b3e authored by Alexander Gehrke's avatar Alexander Gehrke
Browse files

[lec02] Add templates

parent e1a1e66b
No related branches found
No related tags found
No related merge requests found
package datastructures
sealed trait List[+A] {
def head = this match {
case Nil => sys.error("head of empty list")
case Cons(a, _) => a
}
def tail: List[A] = ???
def init: List[A] = ???
def setHead[AA >: A](head: AA): List[AA] = ???
def foldLeft[B](z: B)(f: (B, A) => B): B = ???
}
case object Nil extends List[Nothing]
case class Cons[+A](elem: A, rest: List[A]) extends List[A]
object List {
def apply[A](as: A*): List[A] =
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
}
package datastructures
object Parametricity {
// with our compiler settings from build.sbt, there are even less
// possibilities to do something wrong here without the compiler complaining
def para[A,B,C](a: A, b: B)(f: (A,B) => C): C = ???
}
package datastructures
import org.scalatest._
import testutil.PendingIfUnimplemented
class ListSpec extends FlatSpec with Matchers with AppendedClues with PendingIfUnimplemented {
val numbers = List(1 to 5: _*)
val single = List(1)
val strings = List("a", "b", "c")
"A list" should "have a tail function that removes the first element" in {
numbers.tail shouldBe List(2, 3, 4, 5)
single.tail shouldBe Nil
a[RuntimeException] should be thrownBy List().tail
}
it should "have a init function that removes the last element" in {
numbers.init shouldBe List(1, 2, 3, 4)
single.init shouldBe Nil
a[RuntimeException] should be thrownBy List().init
}
it should "have a setHead method, which replaces the first element" in {
numbers.setHead(8) shouldBe List(8, 2, 3, 4, 5)
a[RuntimeException] should be thrownBy List().tail
}
it should "have a left fold" in {
strings.foldLeft("X")(_ + _) should not be "Xcba" withClue ", this looks like a right fold with flipped args"
strings.foldLeft("X")(_ + _) shouldBe "Xabc"
}
}
\ No newline at end of file
package testutil
import org.scalatest._
trait PendingIfUnimplemented extends TestSuiteMixin { this: TestSuite =>
abstract override def withFixture(test: NoArgTest): Outcome = {
super.withFixture(test) match {
case Failed(_: NotImplementedError) => Pending
case other => other
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment