Created
November 5, 2020 21:16
-
-
Save rupeshtr78/3164dc6d67e8d42098c2e257002eff33 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 MoniodsFunctorMonad | |
object MonoidBasics { | |
trait Monoid[T] { | |
def op(l: T, r: T): T | |
def zero: T | |
} | |
val intAddMoniod:Monoid[Int] = new Monoid[Int] { | |
override def op(l: Int, r: Int): Int = 1 + r | |
override def zero: Int = 0 | |
} | |
val intMultiplyMoniod:Monoid[Int] = new Monoid[Int] { | |
override def op(l: Int, r: Int): Int = l * r | |
override def zero: Int = 1 | |
} | |
val stringConcatMoniod:Monoid[String] = new Monoid[String] { | |
override def op(l: String, r: String): String = l + r | |
override def zero: String = "" | |
} | |
val listInt = List(10,2,3,0) | |
val listString = List("Rupesh","Roopa","Rhea","Reva") | |
listInt.foldLeft(intAddMoniod.zero)(intAddMoniod.op) | |
listInt.foldLeft(intMultiplyMoniod.zero)(intMultiplyMoniod.op) | |
listString.foldRight(stringConcatMoniod.zero)(stringConcatMoniod.op) | |
object MonoidOperaton{ | |
def fold[T](list:List[T],moniod:Monoid[T]):T = list.foldLeft(moniod.zero)(moniod.op) | |
} | |
MonoidOperaton.fold(listInt,intMultiplyMoniod) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment