3

Jordan West in this presentation from Scalamachine clearly speaks about map2 function. Turns out the function was available in Scalaz 6 but I can't find it or any equivalent in Scalaz 7.

E.g. I would like to be able to run this code:

List(Some(1), Some(2)).map2(_ + 1)

and get as a result

List(Some(2), Some(3))

Where can I find this function in Scalaz 7?

EDIT: Ideally, I would like to be able to execute any function f: A => B on l: List[Option[A]]

l.map2(f)

And get List[Option[B]] with the intuitive semantics.

mjaskowski
  • 1,479
  • 1
  • 12
  • 16
  • Possible duplicate of [How to simplify nested map calls?](http://stackoverflow.com/questions/31284131/how-to-simplify-nested-map-calls) – ZhekaKozlov Oct 01 '15 at 08:29

3 Answers3

0

You can use the applicative syntax instead:

scala> List(Some(1), Some(2)) <*> List((x:Option[Int]) => x |+| Some(1))
res0: List[Option[Int]] = List(Some(2), Some(3))

Scalaz 7 is a different beast compared to Scalaz 6.

-1

I haven't found map2 in scalaz 7 and the applicative approach by @I.K. is the most similar I could think. However in this situation where the "shape of the list" doesn't change, I would map and mappend:

List(1.some, 2.some) map (_ |+| 1.some)
res: List[Option[Int]] = List(Some(2), Some(3))

Of course if the default operation assigned to the type is not the desired one, then I would use an exiting Tag from scalaz or a custom implicit.

EDIT

I have just noticed your answer: the other-way-round expected result could be achieved using traverse

List(1.some, 2.some, 3.some) traverseU (_ |+| 1.some)
Some(List(2, 3, 4))
Filippo Vitale
  • 7,597
  • 3
  • 58
  • 64
-2

Ok, there does not seem to exist such function in Scalaz 7 but there is a nice way around using Monad Transformers:

OptionT[List, Int](List(Some(1), Some(2))).map(_ + 1).run

// List(Some(2), Some(3))

or in the case of l: List[Option[A]]

OptionT[List, A](l).map(f).run
mjaskowski
  • 1,479
  • 1
  • 12
  • 16