[英]Using functions as applicative functors/cartesians
I'm using the cats
lib for this. 我正在使用
cats
lib。
It's easy enough to combine two lists using their applicative functor instance (or Cartesian
, to be precise): 使用他们的applicative functor实例(或者
Cartesian
,准确地)组合两个列表很容易:
import cats._
import cats.implicits._
(List(23, 4), List(55, 56)).mapN(_ + _)
>> List(78, 79, 59, 60)
However, I can't seem to be able to 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 does work if I do some of the 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 excessively verbose
似乎过于冗长
Edit: I create a worksheet here if you wanna play with it: https://scastie.scala-lang.org/dcastro/QhnD8gwEQEyfnr14g34d9g/2 编辑:如果你想玩它,我在这里创建一个工作表: https : //scastie.scala-lang.org/dcastro/QhnD8gwEQEyfnr14g34d9g/2
This only works if you have partial-unification
enabled. 这仅在您启用了
partial-unification
时才有效。 The easiest way to do so, is to add the sbt-partial-unification
plugin . 最简单的方法是添加
sbt-partial-unification
插件 。
If you're on Scala 2.11.9 or newer, you can also simply add the compiler flag: 如果你使用的是Scala 2.11.9或更高版本,你也可以简单地添加编译器标志:
scalacOptions += "-Ypartial-unification"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.