A functional way to search for empty gaps in a list of tuples with start and end times

Let's say I have a list of tuples with start and end times:

List((1,10), (2,11), (3,11), (13,14))

The only relaxation is that the start time is increasing

I expect the following output:

List((0,1), (11,13))

The procedural implementation is quite simple, however I would not have a hint of this (idiomatically) functioning.

A scala -for-yield does not seem to fit well, as the result will be the same size as the input. While reducing / adding would limit me to having only one tuple as an answer.

+4
source share
2 answers

Consider the following solution:

list
  .foldLeft((List[(Int,Int)](), 0)) {
     case ((res, se), (s, e)) => 
       if(s>se) ((se, s)::res,e) 
       else (res, e)
  }
  ._1
  .reverse

. : ( , List (Int, Int)) ( 0). (s, e) . , , : (se, s)::res

+4

scanLeft

list.scanLeft((0,0,0))((l,r) => 
  if(r._1 > l._3) {(l._2, r._1, r._2)} 
  else {(l._1,r._2, r._2)}) 
filter(x => x._2 != x._3) 
map(x => (x._1, x._2))

-, , , , ( (0,0,0) ), , , , ,

  • , .

, , , , , , (- ), by

  • , 2.

, , (, if-). . , , .

0

All Articles