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

查看:84
本文介绍了Scala:zipWith [A,B,C](f:Function2 [A,B,C],l1:列表[A],l2:列表[B]):列表[C]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要实现一个需要两个列表和一个函数的函数。然后,该函数使用两个列表的元素,并将该函数应用于元素,并使用map和/或fold以及列表类中的函数将其保存到列表中。



示例:



•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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆