Last active
July 2, 2017 11:02
-
-
Save richashworth/fe40cc37088c302617dd113ad4710807 to your computer and use it in GitHub Desktop.
This file contains 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 $ivy.`org.typelevel::cats:0.9.0`, cats.Semigroup | |
// Our domain entity | |
case class Company(name: String, value: Int) | |
// Some example data | |
val c1 = Company("A", 10) | |
val c2 = Company("B", 20) | |
val c3 = Company("C", 30) | |
val c4 = Company("D", 40) | |
val cs = List(c1, c2, c3, c4) | |
// Semigroups describe an aggregation pattern. | |
// We provide two such context-specific aggregations below: | |
implicit val CompanyMergeSemigroup = new Semigroup[Company] { | |
def combine(t1: Company, t2: Company) = | |
Company(t1.name + t2.name, t1.value + t2.value) | |
} | |
implicit val EliminateCompetitorsSemigroup = new Semigroup[Company] { | |
def combine(t1: Company, t2: Company) = Set(t1, t2).maxBy(_.value) | |
} | |
import Semigroup._ | |
// Need to explicitly pass the semigroup instance if there is more than one in scope | |
val r1 = combineAllOption(cs)(CompanyMergeSemigroup) | |
val r2 = combineAllOption(cs)(EliminateCompetitorsSemigroup) | |
val r3 = combineAllOption(List())(EliminateCompetitorsSemigroup) | |
println(r1) | |
// Some(Company(ABCD,100)) | |
println(r2) | |
// Some(Company(D,40)) | |
println(r3) | |
// None |
This file contains 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
// We can use inline syntax for combine | |
import cats.implicits._ | |
import $file.Semigroups, Semigroups.Company | |
val c1 = Company("Market Leader", 1000) | |
val c2 = Company("Competitor A", 500) | |
val c3 = Company("Competitor B", 900) | |
import Semigroups.EliminateCompetitorsSemigroup | |
// The implicit semigroup instance that is in scope will be used for the aggregation | |
println(c1 |+| c2 |+| c3) | |
// Company(Market Leader,1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment