Commit a31e87bf authored by Tim Hegemann's avatar Tim Hegemann
Browse files

add task sheet 4

parent 4f05a877
......@@ -12,6 +12,7 @@ usually marked with `???`.
| 1: Functional Data Structures | \<no templates\> |
| 2: Error Handling | [`fp02`](src/main/scala/fp02) |
| 3: Strictness and Laziness | [`fp03`](src/main/scala/fp03) |
| 4: Laws, Monoids, and Foldable | [`fp03`](src/main/scala/fp04) |
## Usage tips:
To keep your local solutions to the exercises when pulling from the repository,
......
package fp04
import scala.language.higherKinds
trait Monoid[A] {
def zero: A
def op(a1: A, a2: A): A
}
object Monoid {
def foldMapBalanced[A,B](as: IndexedSeq[A], m: Monoid[B])(f: A => B): B =
if(as.isEmpty)
m.zero
else if (as.length == 1)
f(as(0))
else {
val (left, right) = as.splitAt(as.length / 2)
m.op(foldMapBalanced(left, m)(f), foldMapBalanced(right, m)(f))
}
def endoMonoid[A]: Monoid[A => A] = new Monoid[A => A] {
override def zero: A => A = a => a
override def op(a1: A => A, a2: A => A): A => A = a2 andThen a1
}
def dual[A](M: Monoid[A]): Monoid[A] = new Monoid[A] {
override def zero: A = M.zero
override def op(a1: A, a2: A): A = M.op(a2, a1)
}
// AUFGABE 1: Monoid-Instanz für Funktionen
def functionMonoid[A, B](B: Monoid[B]): Monoid[A => B] = ???
}
trait Foldable[F[_]] {
import Monoid._
// AUFGABE 3: Foldable
def foldRight[A, B](as: F[A])(z: B)(f: (A, B) => B): B = ???
def foldLeft[A, B](as: F[A])(z: B)(f: (B, A) => B): B = ???
def foldMap[A, B](as: F[A])(f: A => B)(mb: Monoid[B]): B
def concatenate[A](as: F[A])(m: Monoid[A]): A =
foldLeft(as)(m.zero)(m.op)
def toList[A](as: F[A]): List[A] =
foldRight(as)(List[A]())(_ :: _)
}
object Foldable {
// AUFGABE 2: Foldable-Instanz für Option
def optionFoldable: Foldable[Option] = ???
}
package fp04
sealed trait WC
case class Stub(chars: String) extends WC
case class Part(lStub: String, words: Int, rStub: String) extends WC
object WC {
val wcMonoid: Monoid[WC] = new Monoid[WC] {
override val zero = ???
override def op(a: WC, b: WC) = ???
}
def count(str: String): Int = ???
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment