A list or array of monoid type A is a monoid too. Now I would like to combine arrays of integers using cats.
scala> 1 |+| 2
res1: Int = 3
scala> Array(1, 2, 3) |+| Array(1, 2, 3)
<console>:21: error: value |+| is not a member of Array[Int]
Array(1, 2, 3) |+| Array(1, 2, 3)
I would like to get Array(2, 4, 6) as a result of Array(1, 2, 3) |+| Array(1, 2, 3) instead. How can I do that ?
combine on a Seq or an Array usually means appending them to create a new Collection.
However, you can do what you're trying to do by defining your own Monoid, with zip instead of append. Here's something I came up with on the fly:
implicit val zipArrayMonoid = new Monoid[Array[Int]] {
override def combine(x: Array[Int], y: Array[Int]) = {
x.zip(y).map {
case (a, b) => a + b
}
}
override def empty = Array.empty
}
This will cause arrays of different sizes to have their additional values ignored (as that's what the zip implementation does, you can check the docs here)
Here's a scalaFiddle with the result: https://scalafiddle.io/sf/YzdUl4L/0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With