Skip to content

Instantly share code, notes, and snippets.

@Mishkun
Created March 10, 2019 14:57
Show Gist options
  • Save Mishkun/c150c24b1905476c5968a6281018f0c3 to your computer and use it in GitHub Desktop.
Save Mishkun/c150c24b1905476c5968a6281018f0c3 to your computer and use it in GitHub Desktop.
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