清洁过滤Eithert的列表以查找子类型的值

发布于 2025-01-22 09:20:42 字数 656 浏览 5 评论 0原文

我有一个eithert值列表。我想确定此列表中特定子类型的正确值。以下提供了一个玩具示例。

import cats.effect.IO
import cats.implicits._

sealed trait Animal {
  def name: String
}
case class Cat(name: String) extends Animal
case class Dog(name: String) extends Animal

val listOfAnimals: List[Either[Throwable, Animal]] = List(Right(Cat("Snowball")), Right(Dog("Mr. Growls")))

listOfAnimals
  .map(_.toEitherT[IO])
  .existsM(_ exists {
      case _: Cat => true
      case _      => false
    })
  .unsafeRunSync()

到目前为止,我提出的最清洁代码是上述的使用用法。是否有更干净 /更简洁的方式?请注意,i 不想对eithert值列表进行测序。

I have a list of EitherT values. I would like to determine if a Right value of a specific subtype exists in this list. The following provides a toy example.

import cats.effect.IO
import cats.implicits._

sealed trait Animal {
  def name: String
}
case class Cat(name: String) extends Animal
case class Dog(name: String) extends Animal

val listOfAnimals: List[Either[Throwable, Animal]] = List(Right(Cat("Snowball")), Right(Dog("Mr. Growls")))

listOfAnimals
  .map(_.toEitherT[IO])
  .existsM(_ exists {
      case _: Cat => true
      case _      => false
    })
  .unsafeRunSync()

The cleanest code I have come up with so far is the above existsM usage. Is there a cleaner / more concise way? Note that I do not want to sequence the list of EitherT values.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文