Skip to content
Snippets Groups Projects
Commit 7d698f12 authored by Felix Herrmann's avatar Felix Herrmann
Browse files

[lec07] create exercies and tests

parent add34dfd
No related branches found
No related tags found
No related merge requests found
......@@ -4,6 +4,12 @@ import scala.language.higherKinds
trait Monad[F[_]] {
def unit[A](a: A): F[A]
def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B]
def map2[A, B, C](fa: F[A], fb: F[B])(f: (A, B) => C): F[C] = ???
def sequence[A](fas: List[F[A]]): F[List[A]] = ???
def compose[A, B, C](f: A => F[B])(g: B => F[C]): A => F[C] = ???
}
trait Functor[F[_]] {
......
......@@ -2,6 +2,7 @@ package monads
final case class Id[A](value: A)
object Id {
// No tests. If it compiles, it's correct.
implicit val idMonad = new Monad[Id] {
def unit[A](a: A): Id[A] = ???
def flatMap[A, B](fa: Id[A])(f: A => Id[B]): Id[B] = ???
......
package monads
import org.scalatest._
import testutil.PendingIfUnimplemented
class MonadFunctorSpec extends FlatSpec with Matchers with AppendedClues with PendingIfUnimplemented {
"functorFromMonad" should "return a working functor" in {
Functor.functorFromMonad[Option](new Monad[Option] {
def unit[A](a: A): Option[A] = Some(a)
def flatMap[A, B](fa: Option[A])(f: A => Option[B]): Option[B] =
fa.flatMap(f)
}).map[Int, String](Some(3))(_.toString) shouldBe Some("3")
}
}
package monads
import org.scalatest._
import testutil.PendingIfUnimplemented
class MonadSpec extends FlatSpec with Matchers with AppendedClues with PendingIfUnimplemented {
"map2" should "combine two monadic values" in {
tupleMonad.map2(Tuple1(1), Tuple1(2))((a, b) => a + b) shouldBe Tuple1(3)
}
"sequence" should "correctly sequence all values" in {
tupleMonad.sequence(List(
Tuple1(1),
Tuple1(2),
Tuple1(3)
)) shouldBe Tuple1(List(1,2,3))
}
"compose" should "correctly compose monad functions" in {
val f: Int => Tuple1[Double] = a => Tuple1(a/2.0)
val g: Double => Tuple1[String] = a => Tuple1(a.toString)
tupleMonad.compose(f)(g)(3) shouldBe Tuple1("1.5")
}
val tupleMonad = new Monad[Tuple1] {
def unit[A](a: A): Tuple1[A] = Tuple1(a)
def flatMap[A, B](fa: Tuple1[A])(f: A => Tuple1[B]): Tuple1[B] =
f(fa._1)
}
}
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