Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine arrays of monoid type?

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 ?

like image 756
Michael Avatar asked Dec 12 '25 02:12

Michael


1 Answers

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

like image 54
Luka Jacobowitz Avatar answered Dec 13 '25 17:12

Luka Jacobowitz