Last active
December 28, 2015 00:39
-
-
Save aoiroaoino/7414727 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
trait Monoid[A] { | |
def mzero: A | |
def mappend(a: A, b: A): A | |
} | |
trait FoldLeft[F[_]] { | |
def foldLeft[A, B](xs: F[A], b: B, f: (B, A) => B): B | |
} | |
object Monoid { | |
implicit val intMonoid = new Monoid[Int] { | |
def mzero = 0 | |
def mappend(a: Int, b: Int): Int = a + b | |
} | |
implicit val stringMonoid = new Monoid[String] { | |
def mzero = "" | |
def mappend(a: String, b: String): String = a + b | |
} | |
} | |
object FoldLeft { | |
implicit val foldLeftList = new FoldLeft[List] { | |
def foldLeft[A, B](xs: List[A], b: B, f: (B, A) => B): B = xs.foldLeft(b)(f) | |
} | |
implicit val foldLeftVector = new FoldLeft[Vector] { | |
def foldLeft[A, B](xs: Vector[A], b: B, f: (B, A) => B): B = xs.foldLeft(b)(f) | |
} | |
} | |
def sum[M[_]: FoldLeft, A: Monoid](xs: M[A]): A = { | |
val m = implicitly[Monoid[A]] | |
val fl = implicitly[FoldLeft[M]] | |
fl.foldLeft(xs, m.mzero, m.mappend) | |
} | |
import Monoid._ | |
import FoldLeft._ | |
sum(List(1,2,3)) | |
//=> 6 | |
sum(List("a", "b", "c")) | |
//=> "abc" | |
sum(Vector(1,2,3)) | |
//=> 6 | |
sum(Vector("a", "b", "c")) | |
//=> "abc" | |
//sum(List('a', 'b', 'c')) | |
//=> error | |
//sum(Array(1, 2, 3)) | |
//=> error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment