如何将Map转换为Traverse

时间:2014-10-06 13:09:57

标签: scala scalaz

有没有办法将Map转换为Traverse

目的是致电map.traverseS(…)

错误是

<console>:16: error: value traverseS is not a member of    scala.collection.immutable.Map[String,Int]

1 个答案:

答案 0 :(得分:2)

Map已有Traverse个实例:

import scalaz._, Scalaz._
val m = Map(1 → "a", 2 → "b")
println(m.traverseS({ s => State({ f: Float => (f, s+f) }) }).run(1.0f))

打印

(1.0,Map(1 -> a1.0, 2 -> b1.0))

如果要遍历(键,值)对,可以使用.toList

println(m.toList.traverseS({
  case (k, v) => State({ f: Float => (f + k, v + f) }) }).run(1.0f))

打印

(4.0,List(a1.0, b2.0))