2010-04-01 17 views
7

C'è un trait chiamato Kleisli nella libreria scalaz. Guardando il codice:Scalaz Kleisli domanda

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

Chiamando la funzione k con il valore di 2 dà:

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

La mia domanda è: come avrei usato Scalaz per combinare F e G per ottenere una funzione m in modo tale che l'uscita di m (2) sarebbe:

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

questo è anche possibile?

risposta

3

Sembra che tu voglia transpose. Scalaz non fornisce questo, ma dovrebbe essere facile da scrivere. La funzione m che si desidera è val m = f andThen (_.map(g)) andThen transpose andThen (_.join)

+0

Non riesco a provare questo al momento, ma non è possibile utilizzare la sequenza MA # per eseguire la trasposizione? http://scalaz.googlecode.com/svn/continuous/latest/browse.sxr/scalaz/example/ExampleTraverse.scala.html – retronym

+0

Hai ragione. È assolutamente possibile, data l'istanza applicativa "zippy" per flussi (o ZipStream). – Apocalisp

+0

Oops, no, non ha il comportamento giusto. – Apocalisp