Created
March 12, 2018 23:08
-
-
Save n4to4/22f41f49893c604faca315b36d0cdfca to your computer and use it in GitHub Desktop.
Fold
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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