Passing each element of a List to a function in Scala

Viewed 727

Issue: I am trying to pass each element of list to a function in Scala

Need to pass elements of myList to arg y in the add function, here x has a constant value which is 5

def add(x: Int, y: Int): Int = x + y
val myList = List(2,3,4)

Expected Output: 7 8 9

3 Answers

Use map to apply the function add to each element in myList which returns a new List.

scala> val x = 5
val x: Int = 5

scala> myList.map(myListElement => add(x,myListElement))
val res19: List[Int] = List(7, 8, 9)

Here's a recursive way of doing it:

def sum(x: Int = 5, y: Int): Int = x + y

def sumElem(xs: List[Int]): List[Int] = {
  @scala.annotation.tailrec
  def sumElemAcc(xs: List[Int], sumXS: List[Int]): List[Int] = {
    if (xs.isEmpty) sumXS
    else sumElemAcc(xs.tail, sumXS :+ sum(y = xs.head))
  }
  sumElemAcc(xs, List())
}

val myList = List(2,3,4)

sumElem(myList)

Output:

res0: List[Int] = List(7, 8, 9)

All answers work fine but if you want to do things in more functional style and different approach consider trying following:

def add(x:Int,y:Int):Int = x+y
val add_5 = (y:Int) => add(5,y)
val li = List(1,2,3)
li.map(add_5) // for me mapping function like this is more intuitive i.e. without arguments 

If you want to try curried and partially applied ways. Consider trying one of the followings also:

//example of eta expansion is x=> f(x)
  val simpleAddFun = (x:Int, y:Int) => x+y  //this is a fn that will be eta expanded
  def simpleAddMethod(x:Int, y:Int) = x+y //this is method
  def curriedAddMethod(x:Int)(y:Int) = x+y //this is curried method

  //Implement add7
  val add_7 = (y:Int) => simpleAddFun(7,y)
  //or simply
  val add_7_2 = simpleAddFun.curried(7)

  //or we can tell compiler to do eta expansion.... by _ at last of curried method
  val add_7_eta = curriedAddMethod(7)_  //we can say it partially applied fn
  val add_7_eta2 = curriedAddMethod(7)(_) //alternative syntax also works for non curried fns/methods

  //using simple methods/fns like curried..
  val add_7_sim = simpleAddFun(7, _:Int)
  val add_7_sim2 = simpleAddMethod(7, _:Int)

Although currying and partially applied functions are rarely used in writing real world apps and things can also be done without them. But sometimes knowing them makes your code look more clean and matured. Consider using official doc for more clarity.

Related