Mám tieto dve funkcie, napísané v scala:
def f: (Int,Int) => Int = (x,y) => x+y
def g: Int=>Int=>Int=x=>y=>x+y
Teraz chcem napísať funkciu, ktorá curres funkcie f, pričom jeden argument, do funkcie g, pričom dva argumenty.
Okrem definície nemôžem nájsť riešenie tohto problému
curry: ((Int, Int) => Int) => (Int => Int => Int):
Nejaké návrhy?
odpovede:
1 pre odpoveď č. 1scala> 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
3 pre odpoveď č. 2
Môžete jednoducho použiť curried
fungujú?
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
Upraviť: príklad a curry
Funkcia založená na zdrojovom kóde curried
v Function2
:
def curry[A,B,C](f: (A,B) => C): A => B => C = (x1: A) => (x2: B) => f(x1,x2)