Diullei
Diullei

Reputation: 12414

Compare two lists - Scala

what is the best way to verify the greater list value using scala?

example:

Verify if List(1, 2, 3) is greater than List(2, 3, 4)

I tried create a function:

def listGt[T](li:List[T], l2:List[T]) = li > l2

but I got a message: error: value > is not a member of List[T]

Upvotes: 2

Views: 2210

Answers (2)

user4298319
user4298319

Reputation: 432

If you want to compare lengths of 3D vectors the following may return not what you want:

import Ordering.Implicits._
println(List(2, 3, 4) > List(-2, -3, -4)) // prints true, but lengths are equal

May be this will suit:

object Main {

  def main(args: Array[String]): Unit = {
    val res = listGt(List(1, 2, 3), List(2, 3, 4))
    println(res) // false
    val res2 = listGt(List(2, 3, 4), List(1, 2, 3))
    println(res2) // true
  }

  implicit def coordsToLength[T <% Double](li: List[T]) = math.sqrt(li.foldLeft(0.0)(_ + math.pow(_, 2)))

  def listGt[T <% Double](li: List[T], l2: List[T]) = li > l2
}

Upvotes: 2

wingedsubmariner
wingedsubmariner

Reputation: 13667

For complex reasons, you have to do an import before comparing List and many other collections:

import Ordering.Implicits._

Once you do so life is happy:

List(1) < List(2) // true
List(List(2), List(1)).sorted // swaps order as expected

Upvotes: 4

Related Questions