So I tried to write a curried function, but my solution adds an additional brace for each parameter:
val multiply = {a: Int -> {b: Int -> a * b }}
fun main(args: Array<String>) { println(multiply(2)(3)) // Prints 6 val numbers = arrayOf(1,2,3,4) val twice = multiply(2) println(numbers) // Why does this print garbage? println(numbers map twice) // ...but this works and prints [2,4,6,8] ? }
So I have these three questions:
- Is there a better way to do this?
- Why does println work for the mapped array but not for the plain array?
- Are compile time annotations powerful enough to implement a “curry” annotation that compiles function in multiple ways but still keeps the IDE’s syntax check support working? So that this…
fun main(args: Array<String>) { println(multiply(2,3)) // Prints 6 val numbers = arrayOf(1,2,3,4) val twice = multiply(2) println(numbers) // Why does this print garbage? println(numbers map twice) // ...but this works? }
curried fun multiply(a: Int, b: Int): Int { a * b }
Would pass the IDE’s syntax check and compile to something like this:
[...]
fun multiply():... { return {a: Int ->{b: Int a * b }} }
fun multiply(a: Int): (Int) -> Int { return multiply()(a) }
fun multiply(a: Int, b: Int): Int { return multiply(a)(b) }