scala - 三个列表与猫的笛卡尔积
问题描述
假设我需要压缩三个列表以获取三元组列表。我可以这样写:
import cats._
import cats.data._
import cats.implicits._
(List(1, 2) |@| List(3, 4) |@| List(5, 6)) map {case (a, b, c) => (a, b, c)}
res1: List[(Int, Int, Int)] = List((1,3,5), (1,3,6), (1,4,5), (1,4,6), (2,3,5), (2,3,6), (2,4,5), (2,4,6))
你能简化它吗?
解决方案
With 1.1.0
, it's simply (a, b, c).tupled
. Ammonite script with all the imports and dependencies:
@ import $ivy.`org.typelevel::cats-core:1.1.0`
@ import cats._, cats.data._, cats.implicits._
val triples = (List(1, 2), List(3, 4), List(5, 6)).tupled
println(triples)
Output:
List((1,3,5), (1,3,6), (1,4,5), (1,4,6), (2,3,5), (2,3,6), (2,4,5), (2,4,6))
I wouldn't call it a "zip", however, it's rather a Cartesian product.
推荐阅读
- android - 在弹出窗口中定位滚动视图
- javascript - 如何获取位于其他对象内部的对象的值
- assembly - Qualcomm Hexagon:矢量内存负载内在?
- python - ModuleNotFoundError:没有名为“dash.html”的模块
- java - 如何将 HashMap 转换为具有特定格式的字符串?(JAVA)
- blockchain - 入驻是什么意思?
- spring - Spring如何重用关系上的规范
- java - 获取不受支持的字段:在 Java Spring Boot 中使用 DateTimeFormatter 时的 DayOfMonth
- python - numpy数组中所有元素的范围
- python - 在 tkinter 中删除特定的小部件