Skip to content

Instantly share code, notes, and snippets.

@n4to4
Created March 12, 2018 23:08
Show Gist options
  • Select an option

  • Save n4to4/22f41f49893c604faca315b36d0cdfca to your computer and use it in GitHub Desktop.

Select an option

Save n4to4/22f41f49893c604faca315b36d0cdfca to your computer and use it in GitHub Desktop.
Fold
import cats._
import cats.implicits._
object Main extends App {
case class Fold[I, O, M: Monoid](
tally: I => M,
summarize: M => O
)
object Fold {
def fold[I, O, M: Monoid](F: Fold[I, O, M])(is: List[I]): O =
F.summarize(Foldable[List].combineAll(is.map(F.tally)))
}
case class Average[A: Numeric](
numerator: A,
denominator: Int
)
implicit def x[A: Numeric]: Monoid[Average[A]] = new Monoid[Average[A]] {
def empty = Average(implicitly[Numeric[A]].zero, 0)
def combine(x: Average[A], y: Average[A]): Average[A] =
Average(
implicitly[Numeric[A]].plus(x.numerator, y.numerator),
x.denominator + y.denominator
)
}
def average: Fold[Int, Double, Average[Int]] =
Fold(i => Average(i, 1), a => a.numerator.toDouble / a.denominator)
println(
Fold.fold(average)((1 to 10).toList)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment