Scala corresponds example

The “corresponds” function lets you match up items between two lists. For a good use of this, imagine you have a list of values, and a list of ranges (e.g. numeric or time windows):

val a = List(1, 2, 3, 4)
val b = List((1,4), (2,5), (3,7), (3,11))

From that, you can write a function that compares one item to a range tuple:

val cmp = 
  (k: Int, v: (Int, Int)) => { 
    val (start, end) = v 
    k >= start && k < end 
  }

cmp: (Int, (Int, Int)) => Boolean = 

And then call corresponds (note the two sets of parenthesis):

scala> a.corresponds(b)(cmp)

res22: Boolean = true

This works as expected. If the arrays aren’t of the same length, you’ll also get ‘false’ as expected:

val a = List(1,2,3)

a.corresponds(b)(cmp)
res24: Boolean = false

One Reply to “Scala corresponds example”

Leave a Reply

Your email address will not be published. Required fields are marked *