Search code examples
scalafunctional-programmingarraybuffer

Compare ArrayBuffer[Array[String]] with Scala in FP way


I need to compare two collections of type ArrayBuffer[Array[String]] using a pure functional programming.

e.g.

ArrayBuffer(Array("str1"), Array("str2"), Array("str3"))
// compare with
ArrayBuffer(Array("str1"), Array("str2"), Array("str3"))

I have a solution for ArrayBuffer[String]:

  def sameAs[A](c: Traversable[A], d: Traversable[A]): Boolean =
    if (c.isEmpty) d.isEmpty
    else {
      val (e, f) = d span (c.head !=)
      if (f.isEmpty) false else sameAs(c.tail, e ++ f.tail)
    }

Solution

  • If we want to check whether two traversables of values in type A is the same, we have to have an ordering in the data type A or a function to check whether two values of the type A is the same.

    The solution: at first, having some way to check whether two arrays are the same (by writing an ordering or a function) and next, writing a function to check whether two traversables of Array[T] are the same.

    The below function checks whether two arrays are the same:

    def isTheSameArray[T](xs: Array[T], ys: Array[T])(implicit ordering: Ordering[T]): Boolean = 
      xs.size == ys.size && xs.zip(ys).forall{ case (x, y) => x == y } 
    

    Now we can write the function to check whether two array buffers are the same, as following:

    def isTheSame[T](xs: Traversable[Array[T]], ys: Traversable[Array[T]])(implicit ordering: Ordering[T]): Boolean = 
      if (xs.size != ys.size) false 
      else if (xs.isEmpty == ys.isEmpty) true
      else isTheSameArray(xs.head, ys.head) && isTheSame(xs.tail, ys.tail)