Created
January 26, 2022 05:44
-
-
Save cm-kazup0n/0849d7c9f7b070a203a3f0512a61ee2d 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
package example | |
import cats._ | |
import cats.implicits._ | |
object GroupByAndSort extends App { | |
val parents = List( | |
Parent(5, "p1", Child("p1-c1", 0)), | |
Parent(5, "p1", Child("p1-c2", 1)), | |
Parent(4, "p2", Child("p1-c1", 0)), | |
Parent(4, "p2", Child("p1-c2", 1)), | |
Parent(0, "p3", Child("p3-c1", 0)), | |
Parent(0, "p3", Child("p3-c2", 1)) | |
) | |
final case class Parent(priority: Long, name: String, child: Child*) | |
final case class Child(name: String, priority: Long) | |
//monoidでもいい、その場合はcombineAllのoptionがはずせるけどParentの単位元が何か悩むことになる | |
implicit val semigroup: Semigroup[Parent] = (x: Parent, y: Parent) => | |
//combineしていいのはnameもpriorityも一致しているときに限るので微妙 | |
Parent( | |
name = x.name, | |
priority = x.priority, | |
child = x.child ++ y.child: _* | |
) | |
println( | |
Semigroup | |
.combineAllOption( | |
parents | |
.groupBy(g => (g.name, g.priority)) | |
.values | |
) | |
.map(_.sortBy(_.priority)) | |
) | |
//List( | |
// Parent(0,p3,ArraySeq(Child(p3-c1,0), Child(p3-c2,1))), | |
// Parent(4,p2,ArraySeq(Child(p1-c1,0), Child(p1-c2,1))), | |
// Parent(5,p1,ArraySeq(Child(p1-c1,0), Child(p1-c2,1)))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment