2010-12-30 31 views
12

¿Cómo uso State para imitar el comportamiento de List.zipWithIndex? Lo que he encontrado hasta el momento (que no funciona) es:Pregunta básica del estado de Scalaz

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)]) 
} 

Esto se basa muy libremente en la state example. Como ya he dicho, no funciona:

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)) 

puedo conseguir que funcione mediante el cambio de una línea de la declaración de caso:

case x :: xs => (init[Int]) map { s : Int => (x -> s) :: (numberSA(xs) ! (s + 1)) } 

Pero esto sólo se siente mal. ¿Alguien puede ayudar?

EDITAR - más jugar un rato me ha llegado a este

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)) { _ ::: _ } 
    } 
} 

¿Se puede mejorar? ¿Se puede generalizar para envases que no sean List (y, de ser así, qué clases de tipos son necesarios?)

EDIT 2-ahora he generalizado que, aunque un poco clunkily

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)} }) 
} 

O el muy similar:

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)} }) 
} 

Respuesta

9
def index[M[_]:Traverse, A](m: M[A]) = 
    m.traverse[({type λ[x] = State[Int,x]})#λ, (A, Int)](a => 
    state(i => (i + 1, (a, i)))) ! 0 

O incluso ...

def index[M[_]:Traverse, A](m: M[A]) = 
    m.traverse[({type λ[x] = State[Int,x]})#λ, (A, Int)](a => 
    (Lens.self[Int] += 1) map ((a, _)) ! -1 

Ver The Essence of the Iterator Pattern para más en atravesar con Estado.

+0

Y ahí estaba yo, sintiéndome todo listo –