Created
May 20, 2020 20:13
-
-
Save fancellu/abf3f4331fa25cb8fd10a668b08a95a4 to your computer and use it in GitHub Desktop.
Example of Cats Foldable usage
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 cats._ | |
import cats.data._ | |
import cats.syntax._ | |
import cats.implicits._ | |
object CatFold extends App{ | |
// list of Tuple[Int, Double] | |
println(List((20,1.1),(29,2.2)).combineAllOption) | |
case class Thing[A, B](a: A, b: B) | |
//implicit val thingSemigroup=Semigroup.instance[Thing[Int, BigDecimal]]( (t1, t2)=> Thing(t1.a+t2.a, t1.b+t2.b)) | |
//implicit val thingSemigroup2=Semigroup.instance[Thing[Int, Double]]( (t1, t2)=> Thing(t1.a+t2.a, t1.b+t2.b)) | |
// this replaces the above 2 lines in a more generic manner | |
implicit def thingSemigroup3[A: Semigroup, B: Semigroup]=Semigroup.instance[Thing[A, B]]( (t1, t2)=> Thing(t1.a.combine(t2.a), t1.b.combine(t2.b))) | |
println(List(Thing(10,BigDecimal(1.1)), Thing(29,BigDecimal(2.2))).combineAllOption) | |
println(List(Thing(20,1.1), Thing(29,2.2)).combineAllOption) | |
println(List(Thing("20",1.1), Thing("29",2.2)).combineAllOption) | |
println("int list") | |
implicit val foldableList=Foldable[List] | |
val li=List(10,20,30,50,40) | |
println(li.get(2)) | |
println(foldableList.get(li)(2)) | |
println(foldableList.size(li)) | |
println(foldableList.isEmpty(li)) | |
println(foldableList.combineAll(li)) | |
println(li.combineAll) | |
println(foldableList.count(li)(_>15)) | |
println(li.count(_>15)) | |
println(foldableList.find(li)(_>15)) | |
println(li.find(_>15)) | |
println(foldableList.maximumOption(li)) | |
println(li.maximumOption) | |
} |
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
Some((49,3.3000000000000003)) | |
Some(Thing(39,3.3)) | |
Some(Thing(49,3.3000000000000003)) | |
Some(Thing(2029,3.3000000000000003)) | |
int list | |
Some(30) | |
Some(30) | |
5 | |
false | |
150 | |
150 | |
4 | |
4 | |
Some(20) | |
Some(20) | |
Some(50) | |
Some(50) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment