0

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]
Yann Moisan
  • 8,161
  • 8
  • 47
  • 91

1 Answers1

2

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))
lmm
  • 17,386
  • 3
  • 26
  • 37
  • I have the following error : error: could not find implicit value for parameter F0: scalaz.Traverse[scala.collection.immutable.Iterable] println(m.traverseS({ s => State({ f: Float => (f, s+f) }) }).run(1.0f)) – Yann Moisan Oct 06 '14 at 13:32
  • Are you depending on scalaz 7.1? Do you have exactly the imports given here? – lmm Oct 06 '14 at 15:21
  • same imports. scalaz 7.0.4 – Yann Moisan Oct 06 '14 at 20:49
  • Does `.toList` do what you want? Or you could copy the implementation from 7.1. – lmm Oct 07 '14 at 09:01
  • same issue with Scalaz 7.1.0 (scala 2.10.4) – Yann Moisan Oct 08 '14 at 13:31
  • Ah, my answer was for 2.11. Unapply doesn't seem to infer the right thing under 2.10. It's possible to translate the 2.11 code to 2.10 (i.e. explicitly passing the Unapply), but it's not pretty. – lmm Oct 08 '14 at 16:12
  • For some reason you have to give it some help with which type parameter to float. `type M[A] = Map[Int, A]; (m: M[String]).traverseS{ s => State{ f: Float => (f, s+f) } }.run(1.0f);`. Similar approach using type lambda did not work. `(m: ({type λ[a]=Map[Int,a]})#λ[String]).traverseS{ s => State{ f: Float => (f, s+f) } }.run(1.0f)` – drstevens Oct 10 '14 at 19:31
  • @lmm In your example you import `scalaz._` and `Scalaz._`. What should I import precisely if I don't want to import everything? – Antoine Dec 18 '14 at 14:14