Guest User

Untitled

a guest
May 28th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. /*
  2.  
  3. Semigroup: nonempty set with an associaive binary operation
  4. trait Semigroup[A] {
  5. def add(x:A, y:A):A
  6. }
  7.  
  8. Monoid: sets equipped with a special element and a binary operator, so that
  9. the special element acts as an identity for the binary operator,
  10. and the binary operator is associative
  11.  
  12. trait Monoid[A] {
  13. def add(x:A, y:A):A
  14. def unit:A
  15. }
  16. */
  17.  
  18. trait FoldLeft[F[_]] {
  19. def foldLeft[A,B](xs: F[A], b:B, f: (B,A)=>B):B
  20. }
  21.  
  22. object FoldLeft {
  23. implicit object FoldLeftList extends FoldLeft[List]{
  24. def foldLeft[A,B](xs:List[A], b:B, f: (B,A)=>B) = xs.foldLeft(b)(f)
  25. }
  26. }
  27.  
  28. trait Monoid[A] {
  29. def mappend(a:A, b:A):A
  30. def mzero:A
  31. }
  32.  
  33. object Monoid {
  34.  
  35. implicit object StringMonoid extends Monoid[String] {
  36. def mappend(a:String, b:String):String = a + b
  37. def mzero:String = ""
  38. }
  39.  
  40. implicit object IntMonoid extends Monoid[Int] {
  41. def mappend(a: Int, b: Int): Int = a + b
  42. def mzero:Int = 0
  43. }
  44. }
  45.  
  46. import Monoid._
  47. import FoldLeft._
  48.  
  49. object Main {
  50.  
  51. // this sum function take a list of ints then applies the foldleft function
  52. // with the higher-order function that adds one item to the next
  53. def sum(xs: List[Int]): Int = xs.foldLeft(0) { (a,b) => a + b }
  54.  
  55. def sumWithIntMonoid(xs: List[Int]):Int = xs.foldLeft(IntMonoid.mzero) { (a,b) => IntMonoid.mappend(a,b) }
  56.  
  57. def sumWithAbstractMonoid[T](xs:List[T], m:Monoid[T]):T = xs.foldLeft(m.mzero) { (a,b) => m.mappend(a,b) }
  58.  
  59. def sumWithAbstractMonoidImplicit[T](xs:List[T])(implicit m:Monoid[T]):T = xs.foldLeft(m.mzero) { (a,b) => m.mappend(a,b) }
  60.  
  61. def sumUsingFoldLeftList[T](xs:List[T])(implicit m:Monoid[T]):T = FoldLeftList.foldLeft(xs, m.mzero, m.mappend)
  62.  
  63. def sumWithAbstractFoldLeft[M[_], T](xs:M[T])(implicit m:Monoid[T], fl:FoldLeft[M]):T = fl.foldLeft(xs, m.mzero, m.mappend)
  64.  
  65. }
Add Comment
Please, Sign In to add comment