Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Scala way of finding whether all the elements of an Array has same length?

I am new to Scala and but very old to Java and had some understanding working with FP languages like "Haskell".

Here I am wondering how to implement this using Scala. There is a list of elements in an array all of them are strings and I just want to know if there is a way I can do this in Scala in a FP way. Here is my current version which works...

def checkLength(vals: Array[String]): Boolean = {
  var len = -1
  for(x <- conts){
    if(len < 0)
      len = x.length()
    else{
      if (x.length() != len)
        return false
      else
        len = x.length()
    }
  }
  return true;
}

And I am pretty sure there is a better way of doing this in Scala/FP...

like image 525
Teja Kantamneni Avatar asked Feb 08 '10 17:02

Teja Kantamneni


4 Answers

list.forall( str => str.size == list(0).size )

Edit: Here's a definition that's as general as possilbe and also allows to check whether a property other than length is the same for all elements:

def allElementsTheSame[T,U](f: T => U)(list: Seq[T]) = {
    val first: Option[U] = list.headOption.map( f(_) )
    list.forall( f(_) == first.get ) //safe to use get here!
}

type HasSize = { val size: Int }
val checkLength = allElementsTheSame((x: HasSize) => x.size)_

checkLength(Array( "123", "456") )

checkLength(List( List(1,2), List(3,4) ))
like image 152
sepp2k Avatar answered Oct 13 '22 18:10

sepp2k


Since everyone seems to be so creative, I'll be creative too. :-)

def checkLength(vals: Array[String]): Boolean = vals.map(_.length).removeDuplicates.size <= 1

Mind you, removeDuplicates will likely be named distinct on Scala 2.8.

like image 26
Daniel C. Sobral Avatar answered Oct 13 '22 17:10

Daniel C. Sobral


Tip: Use forall to determine whether all elements in the collection do satisfy a certain predicate (e.g. equality of length).

like image 27
Dario Avatar answered Oct 13 '22 16:10

Dario


If you know that your lists are always non-empty, a straight forall works well. If you don't, it's easy to add that in:

list match {
  case x :: rest => rest forall (_.size == x.size)
  case _ => true
}

Now lists of length zero return true instead of throwing exceptions.

like image 22
Rex Kerr Avatar answered Oct 13 '22 17:10

Rex Kerr