[英]How to write a scala function which receives a map function to a generic type
[英]How to write a exstension map inner for a generic iterator in scala without losing type information
我试过了
exstension[A] (f: Iterator[Iterator[A]){
def mapInner[B](f: A => B): Iterator[Iterator[B]
但这会丢失类型信息,因为如果我给它一个 list[list[Int]] 我会返回 Iterator[Iterator[Int]
这个怎么样:
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))
尝试函子和朋友:
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))
这是很多设置,但您可能不必自己做,而是使用像scalaz或cats这样的库,所有这些东西都已经定义了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.