DEV Community

loading...

Discussion on: Daily Challenge #123 - Curry me Softly

Collapse
jbristow profile image
Jon Bristow

Type erasure sucks. Kotlin doesn't escape from that fact.

fun <A, B, C> curry(a: A, f: (A, B) -> C): (B) -> C = { b -> f(a, b) }

fun <A, B> surround(a: A, b: B): String = "$a$b$a"

fun <A, B, C> curryN(a: A, f: (A, Array<B>) -> C): (Array<B>) -> C = { b -> f(a, b) }

fun main() {

    val add12 = curry(12) { a, b: Int -> a + b }
    println("${add12(13)}")


    fun <T> currySurround7(b: T): String = curry<Int, T, String>(7, ::surround)(b)

    println(currySurround7("Some example"))
    println(currySurround7(123))

    fun <T> currySurroundOther(b: T) = curry<String, T, String>("not as elegant", ::surround)(b)
    println(currySurroundOther("Some example"))
    println(currySurroundOther(123))

    fun addAllTimes3(vararg bs: Int) =
        curryN(3) { a, bsInner: Array<Int> -> bsInner.sum().times(a) }(bs.toTypedArray())

    println(addAllTimes3(1, 1, 2, 3, 4))
}