簡體   English   中英

如何在不丟失類型信息的情況下為 scala 中的通用迭代器編寫擴展 map 內部

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM