我正在尝试解码一些真正糟糕的 JSON。每个对象的类型信息都在标记为type、 ie"type": "event"等的字段中编码。我使用Circe进行 JSON 编码/解码。该库使用类型类,其中相关的类型类是def apply(c: HCursor): Decoder.Result[A]. 问题是任何解码器都对类型不变,A. 这是一个具体的例子
sealed trait MotherEvent {
val id: UUID
val timestamp: DateTime
}
implicit val decodeJson: Decoder[MotherEvent] = new Decoder[MotherEvent] {
def apply(c: HCursor) = {
c.downField("type").focus match {
case Some(x) => x.asString match {
case Some(string) if string == "flight" => FlightEvent.decodeJson(c)
case Some(string) if string == "hotel" => // etc
// like a bunch of these
case None => …Run Code Online (Sandbox Code Playgroud) 在Cats或Scalaz中是否存在可在不同容器类型之间进行转换的类型类?例如
似乎FunctionK/ ~>/ NaturalTransformation可能是我正在寻找的,但没有任何实例为他们定义,我不知道为什么.
我最近正在学习猫库,并且遇到过名为NonEmptyList的此类。
阅读了api之后,我不禁想知道是什么使猫的作者创建了一个新类,而不是利用内置的(::)并使用类型类对其进行扩展。它甚至没有在cats github页面上列出,所以我来这里问这个问题。也许是因为cons是List的子类型?(尽管我不知道它的含义)
::和NEL有什么区别?为什么猫的作者不得不写NEL而不是使用::?
我想知道如果有一个typeclass在猫或Scalaz它提供了一个操作是这样的:
def scan[G[_],A,B](zero: B)(g: G[A],f: (A,B) => B):G[B]
Run Code Online (Sandbox Code Playgroud)
或者,如果存在这样的运算符的某种数学定义(类似于Monadfor bind/flatMap).
这样做的想法是typeclass将二进制函数应用于类型构造函数并获取相同类型的构造函数,但使用不同的类型参数(二进制函数返回的相同类型).
我认为与scanLeftScala标准库集合类似.
我试图转换成一个List[Either[Int]]一个来Either[List[Int]]使用traverse的cats.
错误
[error] StringCalculator.scala:19:15: value traverseU is not a member of List[String]
[error] numList.traverseU(x => {
Run Code Online (Sandbox Code Playgroud)
码
import cats.Semigroup
import cats.syntax.traverse._
import cats.implicits._
val numList = numbers.split(',').toList
numList.traverseU(x => {
try {
Right(x.toInt)
} catch {
case e: NumberFormatException => Left(0)
}
})
.fold(
x => {},
x => {}
)
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用traverse而不是traverseU.
配置(用于猫)
lazy val root = (project in file(".")).
settings(
inThisBuild(List(
organization := "com.example",
scalaVersion := "2.12.4",
scalacOptions += "-Ypartial-unification",
version …Run Code Online (Sandbox Code Playgroud) 我奋力关于如何创建的实例Functor[Dataset]...问题是,当你map从A到B了Encoder[B]必须在隐含的范围,但我不知道该怎么做.
implicit val datasetFunctor: Functor[Dataset] = new Functor[Dataset] {
override def map[A, B](fa: Dataset[A])(f: A => B): Dataset[B] = fa.map(f)
}
Run Code Online (Sandbox Code Playgroud)
当然这个代码抛出一个编译错误,因为Encoder[B]不可用,但我不能添加Encoder[B]为隐式参数,因为它会改变map方法签名,我该如何解决?
scala apache-spark scala-cats scala-implicits apache-spark-encoders
我想做一些需要效果的编程(谁不需要:-)。特别是像 scalaz Task 之类的东西来运行一些异步数据检索并产生类似 Future 的效果,该效果将在完成时处理结果。
我注意到 typelevel Cats 现在有Effect Monad但也有 typelevel eff Monad项目。两者都是为了在功能上处理效果。所以现在我可以选择在哪里投资我的时间,我很困惑。
或者我可以同时使用两者,例如在 eff FutureEffect 或 TaskEffect 中包装 cat.Effect。这甚至是个好主意吗?
谢谢
这是一个玩具 Scala 程序,它从控制台读取 10 个数字并将每个数字加 1 打印出来:
import cats._
import cats.effect._
import cats.implicits._
object Main extends IOApp {
def printLine[A](x: A)(implicit show: Show[A]): IO[Unit] =
IO(println(show.show(x)))
def readLine(): IO[String] =
IO(scala.io.StdIn.readLine())
def readInts(n: Int): IO[List[Int]] =
List.fill(n)(readLine().map(_.toInt)).sequence
override def run(args: List[String]): IO[ExitCode] = {
for {
list <- readInts(10)
i <- list
_ <- printLine(i + 1)
} yield ExitCode.Success
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不能编译。我得到:
[error] found : cats.effect.IO[cats.effect.ExitCode]
[error] required: scala.collection.GenTraversableOnce[?]
[error] _ <- printLine(i + 1)
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我正在尝试更改使用猫验证的代码,例如:
case class Example(text: String, image: String)
case class ValidExample(text: String, image: String)
import cats.data.Validated._
import cats.implicits._
def validText(text: String) = if (text.nonEmpty) text.valid else invalid(-1)
def validImage(image: String) = if (image.endsWith(".png")) image.valid else invalid(-1)
val e = Example("test", "test.png")
(validText(e.text), validImage(e.image)).mapN(ValidExample)
Run Code Online (Sandbox Code Playgroud)
哪个工作正常.
但我的更改要求图像字段是一个选项,如:
case class Example(text: String, image: Option[String])
case class ValidExample(text: String, image: Option[String])
import cats.data.Validated._
import cats.implicits._
def validText(text: String) = if (text.nonEmpty) text.valid else invalid(-1)
def validImage(image: String) = if (image.endsWith(".png")) image.valid else invalid(-1)
val e …Run Code Online (Sandbox Code Playgroud) 这或许曾多次被问过,但我找到的建议都没有帮助.
我有一个简单的Scala代码,生成长数取决于一些副作用.我在IO monad中包装东西,但根据最小功率原则,我实际上是在声明我的功能F[_]: Effect.现在代码不会编译,我不明白为什么,请建议可能出错的地方
import cats.effect.{Clock, Effect}
import cats.syntax.all._
import java.util.concurrent.TimeUnit
...
def generateId[F[_]: Effect](rid: Long)(implicit F: Effect[F], clock: Clock[F]): F[Long] =
for {
currentTimeNanos <- clock.realTime(TimeUnit.NANOSECONDS)
tid <- F.delay(Thread.currentThread().getId)
} yield
(tid << 40 /* */ & 0xFFFFFF0000000000L) |
(rid << 16 /* */ & 0x000000FFFFFF0000L) |
(currentTimeNanos & 0x000000000000FFFFL)
Run Code Online (Sandbox Code Playgroud)
[error] /.../package.scala:34:41: value flatMap is not a member of type parameter F[Long]
[error] currentTimeNanos <- clock.realTime(TimeUnit.NANOSECONDS)
[error] ^
[error] /.../package.scala:35:34: value map is not a member of …Run Code Online (Sandbox Code Playgroud) scala ×10
scala-cats ×10
cats-effect ×2
scalaz ×2
apache-spark ×1
either ×1
shapeless ×1
traversal ×1
types ×1
validation ×1