Yann Moisan
Yann Moisan

Reputation: 8281

How to convert a Map to Traverse

Is there a way to convert a Map to a Traverse ?

The aim is to call map.traverseS(…).

Error is

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

Upvotes: 0

Views: 338

Answers (1)

lmm
lmm

Reputation: 17431

Map already has a Traverse instance:

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

prints

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

If you want to traverse the (key, value) pairs you can use .toList

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

prints

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

Upvotes: 2

Related Questions