Last active
August 29, 2015 14:19
-
-
Save akirillov/74ed7a84230f01ce32e5 to your computer and use it in GitHub Desktop.
Pimp my library with monoid operations on list
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 io.datastrophic | |
trait Monoid[A]{ | |
def append(a1: A, a2: A): A | |
def unit: A | |
} | |
object Monoid{ | |
implicit val IntMonoid = new Monoid[Int]{ | |
def append(a1: Int, a2: Int): Int = a1 + a2 | |
def unit: Int = 0 | |
} | |
implicit val StringMonoid = new Monoid[String]{ | |
override def append(a1: String, a2: String): String = a1 concat a2 | |
override def unit: String = "" | |
} | |
} | |
class ExtendedList[A: Monoid](xs: List[A]){ | |
def specialSum(implicit m: Monoid[A]): A = { | |
xs.foldLeft(m.unit)(m.append) | |
} | |
} | |
object ListConversions{ | |
implicit def expandList[A: Monoid](xs: List[A]): ExtendedList[A] = new ExtendedList(xs) | |
} | |
object ImplicitConversionExample { | |
import ListConversions._ | |
import Monoid._ | |
def main(args: Array[String]): Unit ={ | |
println(List(1,2,3,4,5).specialSum) | |
println(List("a", "b", "c", "d").specialSum) | |
//custom operation monoid | |
val multiMonoid: Monoid[Int] = new Monoid[Int] { | |
override def append(a1: Int, a2: Int): Int = a1 * a2 | |
override def unit: Int = 1 | |
} | |
println(List(1,2,3,4,5).specialSum(multiMonoid)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment