我写了以下简单的代码:
import cats.effect.IO
import cats.instances.either._
import cats.syntax.TraverseSyntax
object Test extends App with TraverseSyntax{
val e: Either[String, IO[Int]] = Right(IO(2))
e.sequence //error here
}
Run Code Online (Sandbox Code Playgroud)
不幸的是它拒绝编译
Error:(25, 94) value sequence is not a member of scala.util.Either
Run Code Online (Sandbox Code Playgroud)
你能解释一下原因吗?我导入了either包含的实例Traverse[Either[A, ?]].怎么了?
阿罗哈!:)
能否请别人指出我一个有用的scala / cats教程?最近几天,我一直在努力使课程成为函子,我将在显示器上打一个洞。到目前为止,我找到的所有文档对我都没有帮助。
也许我应该试试Eta ... = D
这是我想变成函子的课程。除了“表演”外,我的行为也不像我预期的那样。
package org.hudelundpfusch.utilites.decisions.data
import cats.{Functor, Show}
import cats.kernel.Eq
import cats.syntax.functor._
import cats.syntax.show._
import scala.reflect.runtime.universe
import scala.reflect.runtime.universe._
case class Fact[T <: Any] (name: String, value: T) (implicit private val paramTypeTagT: WeakTypeTag[T])
extends Equals {
val paramType: universe.Type = paramTypeTagT.tpe
val paramTypeClass: Option[Class[_ <: T]] = if (value != null) {
Some(value.getClass)
} else {
None
}
def map[A, B](fa: Fact[A])(f: A => B): Fact[B] = Fact[B](fa.name, f(fa.value))
override def canEqual(other: Any): Boolean = …Run Code Online (Sandbox Code Playgroud) 我读过有关无标签决赛的内容,我认为这很棒。我想建立自己的这种模式的小例子,并解决了问题。
这是我的代码:
trait Calculator[F[_]] {
def sum(a: Int, b: Int): F[Either[Throwable, Int]]
def minus(a: Int, b: Int): F[Either[Throwable, Int]]
}
object calculatorInstances {
implicit val futureCalculator: Calculator[Future] = new Calculator[Future] {
override def sum(a: Int, b: Int) =
Future {
Try(a + b).toEither
}
override def minus(a: Int, b: Int) =
Future {
Try(a - b).toEither
}
}
}
import calculatorInstances.futureCalculator
def getPlusAndMinus[F[_]: Monad: Calculator](a: Int, b: Int): F[Either[String, Int]] = {
for {
sum <- Calculator[F].sum(a, b)
res <- …Run Code Online (Sandbox Code Playgroud) 假设我有:
val m: Map[String, Int] = Map("one" -> 1, "five" -> 5, "six" -> 6, "nine" -> 9)
Run Code Online (Sandbox Code Playgroud)
我有两个功能:
def isNotDivisibleByTwo(i: Int): ValidatedNec[String, Int] = Validated.condNec(i%2!=0, i, s"$i is divisible by 2.")
def isNotDivisibleByThree(i: Int): ValidatedNec[String, Int] = Validated.condNec(i%3!=0, i, s"$i is divisible by 3.")
Run Code Online (Sandbox Code Playgroud)
我想要一个给我的功能:
def sanitize(m: Map[String, Int]):Map[String, Validated[NonEmptyList[String], Int]] = ???
Run Code Online (Sandbox Code Playgroud)
即它应该返回满足上述两个功能的所有数字,以及所有失败数字及其相关故障的映射。
例如对于给定的列表m,我想得到:
val result = Map(
"one" -> Valid(1),
"five -> Valid(5),
"nine" -> Invalid(NonEmptyList("9 is dividible by 3")),
"six" -> Invalid(NonEmptyList("6 is dividible …Run Code Online (Sandbox Code Playgroud) I stumbled upon this problem when trying to implement a Bifunctior type class for maps (Bifunctor[Map[_, _]]).
Bifunctor is defined like this in cats:
/**
* The quintessential method of the Bifunctor trait, it applies a
* function to each "side" of the bifunctor.
*
* Example:
* {{{
* scala> import cats.implicits._
*
* scala> val x: (List[String], Int) = (List("foo", "bar"), 3)
* scala> x.bimap(_.headOption, _.toLong + 1)
* res0: (Option[String], Long) = (Some(foo),4)
* }}} …Run Code Online (Sandbox Code Playgroud) 我在理解上遇到了问题,如下所示:
def doSomething(): F[String] = {
for {
_ <- Future.traverse(items)(item => doSomeWork(item)) // Future[]
_ <- doSomeOtherWork(42) //F[]
} yield (())
}
Run Code Online (Sandbox Code Playgroud)
该函数doSomeWork看起来像:
def doSomeWork(item: Item): Future[Unit] =
// some work done inside a Future
)
Run Code Online (Sandbox Code Playgroud)
功能doSomeOtherWork工作如下:
def doSomeOtherWork(i : Int): F[Unit]
Run Code Online (Sandbox Code Playgroud)
因此,当我尝试编译时,遇到以下错误:
[error] found : F[Int]
[error] required: scala.concurrent.Future[?]
[error]
[error] ^
[error] type mismatch;
[error] found : scala.concurrent.Future[Nothing]
[error] required: F[Int]
Run Code Online (Sandbox Code Playgroud)
我不允许在这样的 for comp 中混合 F[] 和 Future 吗?
我正在与 Slick 和 Cats 合作。
database.run返回 a Future,但我需要我的类的方法(泛型 on F[_]: Async)来返回 monad F。我可以让它像这样工作
val future = database.run(insertion)
val result = Await.result(future, Duration.Inf)
Async[F].delay(result)
Run Code Online (Sandbox Code Playgroud)
但这肯定不是应该做的方式,因为它阻塞了线程。
有没有合适的方法来做到这一点?
我有以下代码片段:
final case class Configuration(env: Env, user: String, password: String, address: String)
trait DbSetup[F[_]] {
type EnvT[A] = OptionT[F, A]
def system: EnvT[Env]
def user: EnvT[String]
def password: EnvT[String]
def address: EnvT[String]
}
object DbSetup {
def get[F[_] : Monad](s: DbSetup[F]): s.EnvT[Configuration] = ???
}
Run Code Online (Sandbox Code Playgroud)
如何在函数的实现中使用Applicative函数来填充? mapNgetConfiguration
问题:
我想反复从fs2.Stream某些第三方库提供的一些批次中取出一些批次,因此将客户从fs2.Stream自身中抽象出来并简单地给它们F[List[Int]]在它们准备好后立即批处理。
尝试:
我尝试使用fs2.Stream::take并运行一些示例。
一世。
implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global)
val r = for {
queue <- fs2.concurrent.Queue.unbounded[IO, Int]
stream = queue.dequeue
_ <- fs2.Stream.range(0, 1000).covaryAll[IO, Int].evalTap(queue.enqueue1).compile.drain
_ <- stream.take(10).compile.toList.flatTap(lst => IO(println(lst))).iterateWhile(_.nonEmpty)
} yield ()
r.unsafeRunSync()
Run Code Online (Sandbox Code Playgroud)
它打印第一批List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),然后挂起。我预计从0到的所有批次都1000将被打印。
在这里让事情更简单一点是
二、
implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global)
val r = for {
queue <- fs2.concurrent.Queue.unbounded[IO, Int]
stream = …Run Code Online (Sandbox Code Playgroud) 我创建了一个微型工作系统来以最大的多核处理器利用率运行并行作业。它似乎工作正常,但在某些时候,当处理大量作业时,会出现错误(没有错误消息,只是挂起),我怀疑这是低级竞争条件。我无法确定这是否是我用来实现并行性的 cats-effect 的错误,还是 Atomic 或 TrieMap 的错误。
这是一个缩小的实现,可用于说明和测试该问题:
import cats.effect.IO
import java.util.concurrent.atomic.{AtomicBoolean, AtomicLong}
import scala.collection.concurrent.TrieMap
import cats.effect.unsafe.implicits.global
import java.util.concurrent.ConcurrentHashMap
object ThreadingError extends App:
val jobIdsAdded = (0L until 10000L).toList
for (_ <- jobIdsAdded.iterator) {
ParallelJobs.addJob(() => {})
}
while(ParallelJobs.count.get() < 10000L) {
print(s"${ParallelJobs.count.get()}\r")
Thread.sleep(200)
}
object ParallelJobs:
private val allCores = Runtime.getRuntime.availableProcessors()
private val availableCores = allCores - 1
private val assignedTillJobId: AtomicLong = AtomicLong(0L)
val jobsTrieMap: TrieMap[Long, () => Any] = TrieMap.empty[Long, () => Any]
val jobsConcurrentHashMap: ConcurrentHashMap[Long, () …Run Code Online (Sandbox Code Playgroud) 我有以下应用程序,我无法弄明白,为什么运行它两次它打破RT:
val program = for {
_ <- IO { println("Welcome to Scala! What's your name?") }
_ <- IO { println(s"Well hello, foo") }
} yield ()
program.unsafeRunSync()
program.unsafeRunSync()
Run Code Online (Sandbox Code Playgroud)
我运行了两次并得到了两次相同的结果,为什么它会破坏RT?
scala ×11
scala-cats ×11
cats-effect ×2
either ×1
fs2 ×1
future ×1
monads ×1
scala-3 ×1
validation ×1