2010-04-01 3 views
7

Il ya un trait appelé Kleisli dans la bibliothèque scalaz. En regardant le code:Question de Scalaz Kleisli

import scalaz._ 
import Scalaz._ 
type StringPair = (String, String) 

val f: Int => List[String]  = (i: Int) => List((i |+| 1).toString, (i |+| 2).toString) 
val g: String => List[StringPair] = (s: String) => List("X" -> s, s -> "Y") 

val k = kleisli(f) >=> kleisli(g) //this gives me a function: Int => List[(String, String)] 

appel de la fonction k avec la valeur de 2 donne:

println(k(2)) //Prints: List((X,3), (3,Y), (X,4), (4,Y)) 

Ma question est: comment pourrais-je utiliser Scalaz combiner f et g pour obtenir une fonction m de telle sorte que la sortie de m (2) serait:

val m = //??? some combination of f and g 
println(m(2)) //Prints: List((X,3), (X,4), (3,Y), (4,Y)) 

Est-ce même possible?

Répondre

3

On dirait que vous voulez transpose. Scalaz ne fournit pas cela, mais il devrait être facile à écrire. La fonction m que vous voulez est val m = f andThen (_.map(g)) andThen transpose andThen (_.join)

+0

Je ne suis pas capable d'essayer ceci maintenant, mais ne pouvons-nous pas utiliser la séquence MA # pour effectuer la transposition? http://scalaz.googlecode.com/svn/continuous/latest/browse.sxr/scalaz/example/ExampleTraverse.scala.html – retronym

+0

Vous avez raison. Vous pouvez totalement, étant donné l'instance applicative "zippy" pour les flux (ou ZipStream). – Apocalisp

+0

Oups, non, il n'a pas le bon comportement. – Apocalisp