Scala:zipWith [A,B,C](f:Function2 [A,B,C],l1:列表[A],l2:列表[B]):列表[C] [英] Scala : zipWith[A,B,C](f:Function2[A,B,C], l1:List[A], l2:List[B]) : List[C] Method
问题描述
示例:
•zipWith((x:Int,y:Int)=> x + y,列表(1,2,3),列表(4 ,5,6))
→列表(5,7,9)
•zipWith((x:Int,y:Int)=> x,列表(1,2,3),列表(4,5,6))
→列表(1,2,3)
我不知道如何使用传递的函数并将其应用于两个列表。我的想法是压缩两个列表,然后将该函数应用于压缩列表的每个元素。
优雅的解决方案是使用模式匹配:
def zipWith [A,B,C](f:(A,B)=> C,l1:列表[A],l2:列表[B]):列表[C] = {
l1.zip(l2).map {case(x1,x2)=> f(x1,x2)}
}
要解决这个没有模式匹配,只需要直接访问元组的字段:
def zipWith [A,B,C](f:(A,B )=> C,l1:List [A],l2:List [B]):List [C] = {
l1.zip(l2).map(tuple => f(tuple._1, tuple._2))
}
So i need to implement a function that takes two lists and a function. The function then uses the elements of the two lists and applies the function on the elements and saves them into a list by using map and/or fold and the functions from the list class.
Example:
• zipWith((x: Int, y: Int) => x + y, List(1, 2, 3), List(4, 5, 6)) → List(5, 7, 9)
• zipWith((x:Int,y:Int) => x, List(1,2,3), List(4,5,6)) → List(1, 2, 3)
I do not know how to use the passed function and apply it on the two lists. My idea was to zip the two lists and then apply the function on every element of the zipped list.
The elegant solution is using pattern matching:
def zipWith[A, B, C](f: (A, B) => C, l1: List[A], l2: List[B]): List[C] = {
l1.zip(l2).map { case (x1, x2) => f(x1, x2) }
}
To solve this without pattern matching, you'll just need to access the tuple's fields directly:
def zipWith[A, B, C](f: (A, B) => C, l1: List[A], l2: List[B]): List[C] = {
l1.zip(l2).map(tuple => f(tuple._1, tuple._2))
}
这篇关于Scala:zipWith [A,B,C](f:Function2 [A,B,C],l1:列表[A],l2:列表[B]):列表[C]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!