Created
March 10, 2019 14:57
-
-
Save Mishkun/c150c24b1905476c5968a6281018f0c3 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
interface Monoid<T> { | |
operator fun T.plus(other: T): T | |
fun empty(): T | |
} | |
object StringMonoid : Monoid<String> { | |
override fun String.plus(other: String): String = plus(other) | |
override fun empty(): String = "" | |
} | |
/* works now perfectly */ | |
fun <T> Monoid<T>.fold(list: List<T>): T = list.fold(empty()) { x, acc -> x.plus(acc)} | |
fun main(args: Array<String>) { | |
with (StringMonoid) { | |
println("Hello" + empty()) | |
println(fold(listOf("123", "456", "789"))) | |
} | |
} | |
/* 1000 times cooler, but no multiple receivers supported */ | |
fun <T> Monoid<T>.List<T>.Xfold(): T = fold(empty()) { x, acc -> x.plus(acc)} | |
fun Xmain(args: Array<String>) { | |
with (StringMonoid) { | |
println("Hello" + empty()) | |
println(listOf("123", "456", "789").Xfold()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment