Guest User

Untitled

a guest
Jun 18th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. //typeclass example
  2.  
  3. //Note : List already has a sum method working the same way
  4. //List(1,2,3).sum returns 6
  5. //but this example is simpler
  6.  
  7. trait Summable[T] {
  8. def sum(a: T, b: T): T
  9. }
  10.  
  11. //default instances
  12. object Summable {
  13. implicit val intSummable: Summable[Int] = (a: Int, b: Int) => a +b
  14. implicit val stringSummable: Summable[String] = (a: String, b: String) => a +b
  15. }
  16.  
  17. //add sumAll method to Scala List type
  18. implicit class ListWithSumAll[T](list: List[T]){
  19. def sumAll()(implicit summable: Summable[T]): T = {
  20. list.reduceLeft((sum, element) => summable.sum(sum, element))
  21. }
  22. }
  23.  
  24. List(1,2,3).sumAll //6
  25.  
  26. // add your instances here
  27. case class Color(red: Int, green: Int, blue: Int)
  28.  
  29. implicit val colorSummable: Summable[Color] = (c1: Color, c2: Color) => {
  30. val red = (c1.red + c2.red) /2
  31. val green = (c1.green + c2.green) /2
  32. val blue = (c1.blue + c2.blue) /2
  33. Color(red, blue, green)
  34. }
  35.  
  36. List(Color(10,10,10), Color(200, 255, 10), Color(20, 55, 1)).sumAll // Color(62,66,32)
Add Comment
Please, Sign In to add comment