简体   繁体   中英

Simple currying in scala

I have the following two functions, written in scala:

def f: (Int,Int) => Int = (x,y) => x+y
def g: Int=>Int=>Int=x=>y=>x+y

Now I want to write a function that curries the function f, taking one argument, into a function g, taking two arguments.

Beside the definition I cant find a solution to this problem

curry: ((Int, Int) => Int) => (Int => Int => Int):

Any suggestions?

Can you simply use the curried function?

scala> def f: (Int,Int) => Int = (x,y) => x+y
f: (Int, Int) => Int

scala> val g = f.curried
g: Int => (Int => Int) = <function1>

scala> g(1)(2)
res0: Int = 3

Edit: an example of a curry function based on the source code of curried in Function2 :

def curry[A,B,C](f: (A,B) => C): A => B => C = (x1: A) => (x2: B) => f(x1,x2)
scala> def f(x: Int, y: Int) = x + y
f: (x: Int, y: Int)Int

scala> def curry(fn: (Int, Int) => Int) = (x: Int) => (y: Int) => fn(x, y)
curry: (fn: (Int, Int) => Int)Int => (Int => Int)

scala> val g = curry(f)
g: Int => (Int => Int) = <function1>

scala> g(3)(4)
res0: Int = 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM