Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I import for Scalaz' traverse functionalities

Tags:

scala

scalaz

In every examples I read about Scalaz' traverse features, the following imports were done:

import scalaz._
import Scalaz._

It seems I can't use traverseU until I import Scalaz._.

How does Scalaz object inject traverseU to my collections? I'm completely lost in the reference doc.

What should I import if I just want the traverse and traverseU methods?

like image 871
Antoine Avatar asked Dec 18 '14 14:12

Antoine


1 Answers

For collection traverseU func you'll have to import syntax for traverseU (implicit method for TraverseOps), implicit instance of Traverse[C] (for collection type C) and Applicative[R] (for func result type R[X]).

For instance:

import scalaz.syntax.traverse.ToTraverseOps // F[A] => TraverseOps[F, A]
import scalaz.std.list.listInstance // Traverse[List]
import scalaz.std.option.optionInstance // Applicative[Option]

List(1, 2, 3).traverseU{ Option(_) }
// Some(List(1, 2, 3))

In case result type of func is not R[X] with Applicative[R], but some R with Monoid[R] you'll have to import Monoid[R] instance for implicit method Applicative.monoidApplicative:

import scalaz.std.anyVal.intInstance

List(1, 2, 3).traverseU{ identity }
// 6

Note that listInstance is also MonadPlus[List], Zip[List], Unzip[List], etc.

So if you want to get only Traverse[List] for some good reason, you'll have to us it this way:

implicit val traverseList: scalaz.Traverse[List] = scalaz.std.list.listInstance
implicit val applicativeOption: scalaz.Applicative[Option] = scalaz.std.option.optionInstance
like image 184
senia Avatar answered Nov 03 '22 09:11

senia