gpt4 book ai didi

scala - Scala 中 2 个集合的叉积

转载 作者:行者123 更新时间:2023-12-03 14:58:02 26 4
gpt4 key购买 nike

val cross = (for (x<-setA; y<-setB) yield (x,y))

val cross2 = (setA flatMap (x => setB map ((x,_)))

有没有更优雅的方法来使用交叉产品运算符或类似的方法来做到这一点?
例如:
val cross3 = setA cross setB

最佳答案

import scala.collection.Set

class
Crossable[E1](es1: Traversable[E1])
{
def
×[E2](es2: Traversable[E2]): Traversable[(E1, E2)] =
for (e1 <- es1; e2 <- es2) yield (e1, e2)

def
cross[E2](es2: Traversable[E2]): Traversable[(E1, E2)] =
for (e1 <- es1; e2 <- es2) yield (e1, e2)
}


object
Crossable
{
implicit
def
trav2Crossable[E1](es1: Traversable[E1]): Crossable[E1] =
new Crossable[E1](es1)
}


object
CrossableTest
{
def
main(args: Array[String]): Unit = {
import Crossable.trav2Crossable

val es1 = Set(1, 2, 3)
val es2 = List("a", "b", "c")

(es1 × es2) foreach(printf(" %s%n", _))
}
}

% scala -cp . CrossableTest
(1,c)
(2,b)
(3,a)
(2,a)
(1,a)
(3,b)
(3,c)
(1,b)
(2,c)

关于scala - Scala 中 2 个集合的叉积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2725682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com