Scala Curry Benefits

I wanted to clarify the benefits of curry in scala. According to "Programming in Scala Second Edition" - "currying" A way to write functions with several parameter lists. For example def f(x: Int)(y: Int), it is a curry function with two parameters lists. Curried function can be used when transmitting several lists of arguments, as in: f(3)(4). However, you can also write a partial application of curry function, for examplef(3)." "c"

One of the benefits of creating partially applicable features such as

def multiplyCurried(x: Int)(y: Int) = x * y 
def multiply2 = multiplyCurried(2) _

But we can also use partially applied functions without currying

def multiplyCurried(x: Int,y: Int) 
def multiply2 = multiplyCurried(2, _) 

Could you give some examples where currying will show the benefits?

+4
source share
2

, .

, , :

map[S](f: (T) ⇒ S)(implicit executor: ExecutionContext): Future[S]

,

val f2 = f1.map(x => x)

.

, , - Scala, (, ).

, , "" , ,

def withInputStream[T](opener: => InputStream)(f: InputStream => T): T = ...

withInputStream(new InputStream("hello.txt")) { inputStream =>
  readLines(inputStream)
}

+2

:

, :

def sum(f:Int=>Int, a:Int, b:Int) = f(a) + f(b)
def sumInts(a:Int,b:Int)=sum(x=>x,a,b)
def sumCubes(a:Int,b:Int)=sum(x=>x*x*x,a,b)

, :

def sum(f:Int=>Int):(Int,Int)=>Int={
   def sumF(a:Int,b:Int):Int= 
      if(a>b) 0 else f(a)+ sumF(a+1,b)
   sumF
  }

, :

def sumInts=sum(x=>x)
def sumCubes=sum(x=>x*x*x)

:

sumInt(10,11) + sumCubes(3,4)

sumInt sumCubes, :

sum(cube)(3,4)

currying , , :

def sum(f:Int=>Int)(a:Int,b:Int):Int=
  if(a>b) 0 else f(a)+sum(f)(a+1,b)
0

Source: https://habr.com/ru/post/1568965/


All Articles