scala3 如何制作通用的 zipWith 扩展方法

scala3 how to make generic zipWith extension method

我试图制作一个简单的扩展方法 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

我错过了什么?

您可以使用 IterableOnceOps as explained here.

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.