标签: scala-cats

将'A => F [G [B]]'变换为'F [G [A => B]'scala

给定签名功能:A => F[G[B]].有monad实例FG类型.

是否可以将其转换为具有签名的内容:F[G[A=>B]?这种转变有没有通用名称?

换句话说,实施prettify2什么?

def pretiffy(x: String): Future[Option[String]] = Future{if(x == "") None else Some(s">>>$x<<<")}
val pretiffy2: Future[Option[String => String]] = ???
Run Code Online (Sandbox Code Playgroud)

更新:我很欣赏使用猫或scalaz的答案.

functional-programming scala scalaz scala-cats

2
推荐指数
1
解决办法
84
查看次数

如何使用`asRight`创建与猫的任何一个实例

我想在REPL中创建一个Either使用实例asRight:

import cats._
import cats.data._
import cats.implicits._ 

scala> val x = "xxx".asRight
<console>:20: error: value asRight is not a member of String
       val x = "xxx".asRight
                 ^

scala> import cats.syntax.either._
import cats.syntax.either._

scala> val x = "xxx".asRight
<console>:23: error: value asRight is not a member of String
       val x = "xxx".asRight
                 ^
Run Code Online (Sandbox Code Playgroud)

上面的代码有什么问题?可以asRight在REPL中使用吗?

scala either scala-cats scala-repl

2
推荐指数
1
解决办法
870
查看次数

使用Monoid积累错误

假设我有一个函数列表E => Either[Exception, Unit]来调用事件E并累积错误以返回Either[List[Exception], Unit].

type EventHandler = E => Either[Exception, Unit]

import cats.data.NonEmptyList

def fire(
  e: Event, 
  subscribers: List[EventHandler]
): Either[NonEmptyList[Exception], Unit] = ???
Run Code Online (Sandbox Code Playgroud)

我想实现firecats

 import cats.implicits._

 subscribers.foldMap (_ map (_.toValidatedNel))
            .map (.toEither)
            .apply(e)
Run Code Online (Sandbox Code Playgroud)

是否有意义 ?你会如何改进它?
如何更改firesubscribers同时调用?

concurrency scala monoids scala-cats

2
推荐指数
1
解决办法
228
查看次数

适用于Scala猫的Haskell's mapM等效项

猫是否提供与Haskell中的mapM等效的功能?它应该看起来像:

  def mapM[A, B, F[_], Col[_]]
  (col: Col[A])(f: A => F[B])(implicit F: Applicative[F], T: Traverse[Col]): F[Col[B]] = 
    T.sequence[F, B](F.map(col)(f))
Run Code Online (Sandbox Code Playgroud)

不幸的是,我还没有找到任何像这样的函数=(

scala scala-cats

2
推荐指数
1
解决办法
227
查看次数

类路径中缺少符号“typecats.MonadFilter”

我正在阅读有关tagless final 的本教程。

基于此,我将我的依赖项定义为

object Dependencies {
  lazy val scalaTest = "org.scalatest" %% "scalatest" % "3.0.5"
  lazy val cats = "org.typelevel" %% "cats-core" % "1.2.0"
  lazy val monix = "io.monix" %% "monix" % "2.3.3"
  lazy val monixCats = "io.monix" %% "monix-cats" % "2.3.3"
}
Run Code Online (Sandbox Code Playgroud)

以下是我的代码

// future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._

// cats
import cats.Monad
import cats.implicits._

// monix
import monix.eval.Task
import monix.cats._
import monix.cats.reverse._


trait ProductRepository[M[_]] {
  def findProduct(productId: ProductId) : M[Option[Product]]
  def saveProduct(product: Product) …
Run Code Online (Sandbox Code Playgroud)

scala scala-cats monix

2
推荐指数
1
解决办法
1095
查看次数

如何测量 Cats IO 效果中的经过时间?

我想测量 IO 容器内经过的时间。使用普通调用或期货相对容易(例如,类似于下面的代码)

class MonitoringComponentSpec extends FunSuite with Matchers with ScalaFutures {

  import scala.concurrent.ExecutionContext.Implicits.global

  def meter[T](future: Future[T]): Future[T] = {
    val start = System.currentTimeMillis()
    future.onComplete(_ => println(s"Elapsed ${System.currentTimeMillis() - start}ms"))
    future
  }

  def call(): Future[String] = Future {
    Thread.sleep(500)
    "hello"
  }

  test("metered call") {
    whenReady(meter(call()), timeout(Span(550, Milliseconds))) { s =>
      s should be("hello")
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但不确定如何包装 IO 调用

  def io_meter[T](effect: IO[T]): IO[T] = {
    val start = System.currentTimeMillis()
    ???
  }

  def io_call(): IO[String] = IO.pure {
    Thread.sleep(500)
    "hello"
  } …
Run Code Online (Sandbox Code Playgroud)

functional-programming scala scala-cats cats-effect

2
推荐指数
1
解决办法
874
查看次数

Scala Implicit Search

In the Scala with Cats:

import scala.concurrent.{Future, ExecutionContext}
implicit def futureFunctor
  (implicit ec: ExecutionContext): Functor[Future] = …
Run Code Online (Sandbox Code Playgroud)

Whenever we summon a Functor for Future , either directly using Functor.apply or indirectly via the map extension method, the compiler will locate futureFunctor by implicit resolu on and recursively search for an ExecutionContext at the call site. This is what the expansion might look like:

// We write this:
Functor[Future]
// The compiler expands to this first:
Functor[Future](futureFunctor)
// And then to …
Run Code Online (Sandbox Code Playgroud)

scala future implicit scala-cats

2
推荐指数
1
解决办法
68
查看次数

将列表[任务[列表[A]]]转换为任务[列表[A]]

如何在 Scala 中将List[Task[List[Header]]]类型转换为 Task[List[Header]]

我有一个方法返回 Task[List[Header]] 并多次调用 do 它变成 List[Task[List[Header]]]

functional-programming scala scala-cats monix

2
推荐指数
1
解决办法
329
查看次数

MVar tryPut 返回 true 并且 isEmpty 也返回 true

我写了简单的回调(处理程序)函数,我将它传递给异步 api,我想等待结果:

object Handlers {

  val logger: Logger = Logger("Handlers")
  implicit val cs: ContextShift[IO] =
  IO.contextShift(ExecutionContext.Implicits.global)

  class DefaultHandler[A] {

  val response: IO[MVar[IO, A]] = MVar.empty[IO, A]

  def onResult(obj: Any): Unit = {
    obj match {
      case obj: A =>
        println(response.flatMap(_.tryPut(obj)).unsafeRunSync())
        println(response.flatMap(_.isEmpty).unsafeRunSync())
      case _ => logger.error("Wrong expected type")
    }
  }

  def getResponse: A = {
    response.flatMap(_.take).unsafeRunSync()
  }
}
Run Code Online (Sandbox Code Playgroud)

但是由于某种原因, tryPut 和 isEmpty(当我手动调用 onResult 方法时)都返回 true,因此当我调用 getResponse 时,它​​会永远休眠。这是我的测试:

class HandlersTest extends FunSuite {
    test("DefaultHandler.test") {
    val handler = new DefaultHandler[Int]
    handler.onResult(3)
    val …
Run Code Online (Sandbox Code Playgroud)

concurrency scala side-effects scala-cats

2
推荐指数
1
解决办法
121
查看次数

运维代表什么?

在 Scala 社区中,我经常看到,以类结尾的类Ops非常普遍。例如:

ApplicativeErrorIdOps
Run Code Online (Sandbox Code Playgroud)

代表什么Ops

scala scala-cats

2
推荐指数
1
解决办法
67
查看次数