【问题标题】:scala3 how to make generic zipWith extension methodscala3如何制作通用的zipWith扩展方法
【发布时间】:2022-01-01 10:36:33
【问题描述】:

我试图创建一个简单的扩展方法zipWith,它只是将集合C[A] 映射到C[(A, B)],如下所示:

List(1,2,3) zipWith (_ * 2)
// List((1,2), (2,4), (3,6))

我试过这个:

scala> extension[A, C[_] <: Iterable[_]] (s: C[A]) def zipWith[B](f: A => B): C[(A, B)] = s map ((x) => (x, f(x)))
-- Error:
1 |extension[A, C[_] <: Iterable[_]] (s: C[A]) def zipWith[B](f: A => B): C[(A, B)] = s map ((x) => (x, f(x)))
  |                                                                                                       ^
  |                                                       Found:    (x : Any)
  |                                                       Required: A

我错过了什么?

【问题讨论】:

    标签: scala scala-3


    【解决方案1】:

    您可以按照here 的说明使用IterableOnceOps。

    import scala.collection.IterableOnceOps
    
    extension [A, CC[_]](it: IterableOnceOps[A, CC, Any])
      def zipWith[B](f: A => B): CC[(A, B)] =
        it.map(a => (a, f(a)))
    

    你可以看到代码在运行here。

    【讨论】:

      猜你喜欢
      • 2021-03-16
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 2016-10-30
      相关资源
      最近更新 更多