Scalaz Kleisli问题

7

scalaz 库中有一个名为 Kleislitrait。看一下代码:

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

使用值为2调用函数k的结果如下:

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

我的问题是:如何使用Scalaz将f和g组合起来得到一个函数m,使得m(2)的输出结果为:
val m = //??? some combination of f and g
println( m(2) ) //Prints: List((X,3), (X,4), (3,Y), (4,Y))

这真的可行吗?

1个回答

3

看起来你需要transpose。Scalaz没有提供这个函数,但编写起来应该很容易。你想要的函数mval m = f andThen (_.map(g)) andThen transpose andThen (_.join)


我现在无法尝试这种方法,但我们不能使用MA#序列来进行转置吗?http://scalaz.googlecode.com/svn/continuous/latest/browse.sxr/scalaz/example/ExampleTraverse.scala.html - retronym
你说得对。如果使用流的“zippy”应用实例(或ZipStream),完全可以这样做。 - Apocalisp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接