Currying: adding two lists

I am trying to understand currying in scala. The code takes two lists and adds them.

  def append(as:List[Int],bs:List[Int]):List[Int]=as match{

  case Nil=>bs
  case x::xs=> x::append(xs,bs)

}

      

But if I want to write a currying version of this:

def cappend(as:List[Int])(bs:List[Int])=as match{
     case Nil=>bs
     case x::xs=> x::cappend(xs,bs)
   }

      

Is it correct?

+3


source to share


1 answer


In currying, you can define partially application functions, so there is no need to pass all parameters at the same time. For this example, consider the following amendments:

def cappend(as:List[Int])(bs:List[Int]): List[Int] = as match {
     case Nil   => bs
     case x::xs => x::cappend(xs)(bs)
   }

      

Namely, each parameter is enclosed in parentheses (also the recursive function needs a return type, there is no c prefix in the recursive call). Then we define a partially defined function

val a = cappend(List(1,2)) _
a: List[Int] => List[Int] = <function1>

      



which will add List(1,2)

to what List[Int]

will be provided as the second parameter. For example,

a(List(3,4))
res1: List[Int] = List(1, 2, 3, 4)

      

Also note that we may have a more general type signature, not only for lists Int

,

def cappend[T](as:List[T])(bs:List[T]): List[T]

      

+3


source







All Articles