简体   繁体   English

如何在不丢失类型信息的情况下为 scala 中的通用迭代器编写扩展 map 内部

[英]How to write a exstension map inner for a generic iterator in scala without losing type information

I've tried我试过了

exstension[A] (f: Iterator[Iterator[A]){
    def mapInner[B](f: A => B): Iterator[Iterator[B]

but this loses type information since if I give it a list[list[Int]] I get back Iterator[Iterator[Int]但这会丢失类型信息,因为如果我给它一个 list[list[Int]] 我会返回 Iterator[Iterator[Int]

How about this:这个怎么样:

Welcome to Scala 3.2.0-RC2 (17.0.3.1, Java Java HotSpot(TM) 64-Bit Server VM). Type in expressions for evaluation. Or try :help.

scala> import collection.IterableOps

scala> extension[X, I[X] <: IterableOps[X, I, I[X]],
     |           Y, O[Y] <: IterableOps[Y, O, O[Y]]](cc: O[I[X]])
     |   def mapInner[Z](f: X => Z): O[I[Z]] = cc.map(_.map(f))


scala> List(List(1, 2), List(3, 4)).mapInner(_ * 3) val res0: List[List[Int]] = List(List(3, 6), List(9, 12))

scala> Seq(Set(1, 2), Set(3, 4)).mapInner(_ * 3) val res1: Seq[Set[Int]] = List(Set(3, 6), Set(9, 12))

Try functors and friends:尝试函子和朋友:

trait Functor[F[_]]:
  extension [A](fa: F[A]) def fmap[B](fmap: A => B): F[B]

object Functor:
  given Functor[List] with
    extension [A](fa: List[A]) def fmap[B](fmap: A => B): List[B] =
      fa.map(fmap)
  
  given [F[_], G[_]](using F: Functor[F], G: Functor[G]): Functor[[x] =>> F[G[x]]] with
    extension [A](fa: F[G[A]]) def fmap[B](fmap: A => B): F[G[B]] =
      F.fmap(fa)(ga => G.fmap(ga)(fmap))

import Functor.given

val xs = List(1, 2, 3, 4)

val xss = xs.map(x => List(x, x))

val fxss = summon[Functor[[x] =>> List[List[x]]]]

println(fxss.fmap(xss)((a: Int) => a * 2))

It's a lot of setup but likely you don't have to do it yourself and use a library like scalaz or cats where all these things are already defined.这是很多设置,但您可能不必自己做,而是使用像scalaz或cats这样的库,所有这些东西都已经定义了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM