How to curry functions?


#1

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:

  1. Is there a better way to do this?
  2. Why does println work for the mapped array but not for the plain array?
  3. 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) }


#2

https://github.com/MarioAriasC/funKTionale/wiki/Currying


#3

About println: the type of expression `numbers map twice` is List<Int>, when the type of `numbers` itself is Array<Int>. So it works the same way as println in Java.


#4

But why does map change the type of the functor? I would have expected that it only changes what's inside.