Scala 猫,遍历 Seq [英] Scala cats, traverse Seq

查看:58
本文介绍了Scala 猫,遍历 Seq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以遍历Lists

import cats.instances.list._
import cats.syntax.traverse._

def doMagic(item: A): M[B] = ???
val list: List[A] = ???
val result: M[List[B]] = list.traverse(doMagic)

我可以将 Seq 来回转换为 List

And I can convert a Seq back and forth to List

val seq: Seq[A] = ???
val result: M[Seq[B]] = seq.toList.traverse(doMagic).map(_.toSeq)

但是我也可以不用样板来遍历 Seq 吗?

But can I also traverse Seq without the boilerplate?

val seq: Seq[A] = ???
val result: M[Seq[B]] = seq.traverse(doMagic)

或者有什么简单的方法可以获取 Traverse[Seq] 的实例?

Or what's an easy way to get an instance of Traverse[Seq]?

推荐答案

Cats 不为 Seq 提供类型类实例,因此除了自己实现之外,您还需要进行转换.

Cats does not provide typeclass instances for Seq, so besides implementing it yourself you're stuck with the conversion.

至于原因,在(有点旧的)Cats 问题中正在进行讨论.总而言之,您对 Seq 底层特性的了解还不够,无法确保某些类型类实例的规则成立.

As to why, there's an ongoing discussion in an (somewhat old) Cats issue. To sum it up, you won't know enough about Seq underlying characteristics to make sure some of the typeclasses instances laws hold.

没关系,它现在存在,请参阅链接线程

EDIT : Nevermind, it exists now, see linked thread

这篇关于Scala 猫,遍历 Seq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆