【问题标题】:Cartesian product of three lists with cats三个列表与猫的笛卡尔积
【发布时间】:2018-06-13 16:45:24
【问题描述】:

假设我需要压缩三个列表以获取三元组列表。我可以这样写:

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))

你能简化一下吗?

【问题讨论】:

    标签: scala cartesian-product scala-cats


    【解决方案1】:

    对于1.1.0,它就是(a, b, c).tupled。包含所有导入和依赖项的 Ammonite 脚本:

    @ 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)
    

    输出:

    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))
    

    我不会称它为“zip”,但是,它是一个笛卡尔积。

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 2022-12-09
      • 2012-03-24
      • 2013-06-27
      • 1970-01-01
      • 2020-02-03
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多