Scala:zipWith [A,B,C](f:Function2 [A,B,C],l1:List [A],l2:List [B]):List [C]方法 [英] Scala : zipWith[A,B,C](f: Function2[A,B,C], l1 :List[A], l2 :List[B]) : List[C] Method

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

问题描述

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

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.

示例:

zipWith((x: Int, y: Int) => x + y, List(1, 2, 3), List(4, 5, 6)) →列表(5、7、9)

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)) →列表(1、2、3)

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:List [A],l2:List [B]):List [C]方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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