Skip to content

Instantly share code, notes, and snippets.

@markus1189
Created October 25, 2017 08:55
Show Gist options
  • Save markus1189/9d88ed4baad363751b38000501510fe4 to your computer and use it in GitHub Desktop.
Save markus1189/9d88ed4baad363751b38000501510fe4 to your computer and use it in GitHub Desktop.
FP Study Group
trait Monoid[A] {
def zero: A
def op(lhs: A, rhs: A): A
}
def listMonoid[A]: Monoid[List[A]] = new Monoid[List[A]] {
override def zero: List[A] = List()
override def op(lhs: List[A], rhs: List[A]): List[A] =
lhs ++ rhs
}
val stringMonoid: Monoid[String] = new Monoid[String] {
override def zero: String = ""
override def op(lhs: String, rhs: String): String = lhs + rhs
}
stringMonoid.op(stringMonoid.zero, "Hello World")
stringMonoid.op("Hello ", "World")
def functionMonoid[A,B](baseMonoid: Monoid[A]):
Monoid[B => A] = new Monoid[(B) => A] {
override def zero: B => A = x => baseMonoid.zero
override def op(lhs: (B) => A, rhs: (B) => A): B => A =
x => baseMonoid.op(lhs(x), rhs(x))
}
def optionMonoid[A]: Monoid[Option[A]] = new Monoid[Option[A]] {
override def zero: Option[A] = None
override def op(lhs: Option[A], rhs: Option[A]): Option[A] = {
lhs.orElse(rhs)
}
}
def intMonoid: Monoid[Int] = new Monoid[Int] {
override def op(lhs: Int, rhs: Int): Int = lhs + rhs
override def zero: Int = 0
}
(1 to 10).toList.foldLeft(intMonoid.zero)(intMonoid.op)
def concatenate[A](as: List[A], monoid: Monoid[A]): A = as.foldLeft(monoid.zero)(monoid.op)
def foldMap[A,B](as: List[A], monoid: Monoid[B])(f: A => B): B = {
val bs: List[B] = as.map(f)
concatenate(bs, monoid)
}
case class Person(name: String, age: Int)
val persons = List(Person("A", 20), Person("B", 30), Person("C", 40))
foldMap(persons, intMonoid)(_.age)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment