我如何使用State
来模仿 的行为List.zipWithIndex
?到目前为止我想出的(这不起作用)是:
def numberSA[A](list : List[A]) : State[Int, List[(A, Int)]] = list match {
case x :: xs => (init[Int] <* modify((_:Int) + 1)) map { s : Int => (x -> s) :: (numberSA(xs) ! s) }
case Nil => state( (i : Int) => i -> nil[(A, Int)] )
}
这是非常松散地基于状态示例。正如我所说,它不起作用:
scala> res4
res5: List[java.lang.String] = List(one, two, three)
scala> numberSA(res4) ! 1
res6: List[(String, Int)] = List((one,1), (two,1), (three,1))
我可以通过更改 case 语句的一行来使其工作:
case x :: xs => (init[Int]) map { s : Int => (x -> s) :: (numberSA(xs) ! (s + 1)) }
但这只是感觉不对。任何人都可以帮忙吗?
编辑-更多的玩耍让我明白了这一点
def numberSA[A](list : List[A]) : State[Int, List[(A, Int)]] = {
def single(a : A) : State[Int, List[(A, Int)]] = (init[Int] <* modify((_ : Int) + 1)) map { s : Int => List(a -> s) }
list match {
case Nil => state( (_ : Int) -> nil[(A, Int)] )
case x :: xs => (single(x) <**> numberSA(xs)) { _ ::: _ }
}
}
可以改进吗?它是否可以推广到除容器以外的容器List
(如果可以,需要哪些类型类?)
编辑 2 -我现在已经概括了它,虽然有点笨拙
def index[M[_], A](ma : M[A])
(implicit pure : Pure[M], empty : Empty[M], semigroup : Semigroup[M[(A, Int)]], foldable : Foldable[M])
: State[Int, M[(A, Int)]] = {
def single(a : A) : State[Int, M[(A, Int)]] = (init[Int] <* modify((_ : Int) + 1)) map { s : Int => pure.pure(a -> s) }
foldable.foldLeft(ma, state( (_ : Int) -> empty.empty[(A, Int)] ), { (s : State[Int, M[(A, Int)]],a : A) => (s <**> single(a)) { (x,y) => semigroup.append(x,y)} } )
}
或非常相似:
def index[M[_] : Pure : Empty : Plus : Foldable, A](ma : M[A])
: State[Int, M[(A, Int)]] = {
import Predef.{implicitly => ??}
def single(a : A) : State[Int, M[(A, Int)]] = (init[Int] <* modify((_ : Int) + 1)) map { s : Int => ??[Pure[M]].pure(a -> s) }
??[Foldable[M]].foldLeft(ma, state( (_ : Int) -> ??[Empty[M]].empty[(A, Int)] ), { (s : State[Int, M[(A, Int)]],a : A) => (s <**> single(a)) { (x,y) => ??[Plus[M]].plus(x,y)} } )
}