Using Functions as Applicative Functors / Cartesians

I use cats lib for this.

It is easy enough to combine the two lists using the example of their application functor (or Cartesian , to be precise):

 import cats._ import cats.implicits._ (List(23, 4), List(55, 56)).mapN(_ + _) >> List(78, 79, 59, 60) 

However, it seems like I cannot do the same with two functions:

 val strLength: String => Int = _.length (strLength, strLength).mapN(_ + _) >> value mapN is not a member of (String => Int, String => Int) 

It works if I do some implicit conversions explicitly, and if I create a type alias to give the compiler a hand:

 type F[A] = Function1[String, A] val doubleStrLength = catsSyntaxTuple2Cartesian[F, Int, Int]((strLength, strLength)).mapN(_ + _) doubleStrLength("hello") >> 10 

Is there an easier way to do this? Seems overly verbose

Edit: here I create a worksheet if you want to play with it: https://scastie.scala-lang.org/dcastro/QhnD8gwEQEyfnr14g34d9g/2

+5
source share
1 answer

This only works if you enable partial-unification . The easiest way to do this is to add the sbt-partial-unification plugin .

If you are on Scala 2.11.9 or later, you can also just add the compiler flag:

 scalacOptions += "-Ypartial-unification" 
+6
source

Source: https://habr.com/ru/post/1272333/


All Articles