Cats的Monoid实例在合并数组映射时抛出异常

问题描述 投票:1回答:1

我为Map[Int, Array[Int]]定义了一个Monoid实例,并试图使用它来合并此类映射的列表:

import cats.Monoid
import cats.implicits._

implicit val m: Monoid[Map[Int, Array[Int]]] = Monoid[Map[Int, Array[Int]]]

List(
  Map(
    (0 -> Array(8, 9))
  ),
  Map(
    (0 -> Array(10))
  ),
  Map(
    (1 -> Array(30))
  ),
).foldMap(identity)

我希望输出是这样:

Map(
  (0 -> Array(8, 9, 10),
  (1 -> Array(30),
)

但是,代码抛出以下异常:

[error] java.lang.NullPointerException
[error]         at cats.instances.ListInstances$$anon$1.foldMap(list.scala:74)
[error]         at cats.instances.ListInstances$$anon$1.foldMap(list.scala:16)
[error]         at cats.Foldable$Ops.foldMap(Foldable.scala:31)
[error]         at cats.Foldable$Ops.foldMap$(Foldable.scala:31)
[error]         at cats.Foldable$ToFoldableOps$$anon$5.foldMap(Foldable.scala:31)

我尝试使用.reduce(_ |+| _)m.combineAll而不是.foldMap(identity),结果相同。我在做什么错?

scala functional-programming scala-cats category-theory monoids
1个回答
0
投票

要使代码正常工作,您只需要为数组提供适当的Monoid:

//we also need ClassTag because we don't know type yet and arrays aren't generic
implicit def arrayMonoid[T: ClassTag]: Monoid[Array[T]] = new Monoid[Array[T]] {
    override def empty: Array[T] = Array[T]()

    override def combine(x: Array[T], y: Array[T]): Array[T] = x ++ y
}

Cats库默认不为数组提供Monoid

© www.soinside.com 2019 - 2024. All rights reserved.