Home > other >  Scala Curry-Uncurry A Function
Scala Curry-Uncurry A Function

Time:11-30

I am trying to create a function that receives a basic curried adder function with 2 parameters and returns uncurried adder function, and vice versa for the currying function(receives uncurried-returns curried) in scala. I am having a hard time figuring the return types of curried functions , can anyone help out?

def adderCurried(a: Int)(b: Int): Int = a   b

//define a function that returns uncurried version of this function:

val adderUncurried = toAdderUncurried(adderCurried)

adderUncurried(5,6) // returns 11

def adder(a: Int, b: Int): Int = a   b

//define a function that returns curried version of this function:

val adderCurried = toAdderCurried(adder)

adderCurried(5,6) // returns 11

CodePudding user response:

Part of the problem is that you are not calling the curried function correctly:

adderCurried(5,6) // too many arguments (found 2, expected 1)

It should be called in a way that matches the declaration:

def adderCurried(a: Int)(b: Int)

adderCurried(5)(6)

This gives the clue that there are actually two function invocations here. The first invocation (5) returns a function that when called with (6) gives the answer. That second function must take an Int and return an Int so it is Int => Int, and this must be what is returned by adderCurried(5).

So adderCurried takes an Int and returns Int => Int so the type is

Int => (Int => Int)

or just

Int => Int => Int

You can check this as follows:

val check: Int => Int => Int = adderCurried // OK

You should be able to create the signatures for toAdderCurried and toAdderUncurried based on these types.

CodePudding user response:

The toAdderUncurried function will be like this.

def toAdderUncurried(f: Int => Int => Int): (Int, Int) => Int = (x, y) => f(x)(y)

You can call it like this.

toAdderUncurried(adderCurried)(x, y)

And the curry function will be like this.

def curry(f: (Int, Int) => Int): Int => Int => Int = x => y => f(x, y)

you can call it like this

curry(toAdderUncurried(adderCurried))(x)(y)

CodePudding user response:

Let me add Tim answer. Right here you have 2 options of your adder function:

  • curried type Curried = (Int => Int => Int)
  • and uncurried type Uncurried = (Int, Int) => Int

and your signatures of converting functions should looks like:

def toAdderUncurried(adderCurried: Curried): Uncurried = ???
def toAdderCurried(adderUncurried: Uncurried): Curried = ???
  • Related