Return and recurring harvest using scala

I have a DateTime and TimeSpan class in Scala (suppose the <and + operators work as they should). I am trying to define a range function that takes a start / stop time and a period of time for a step. In C #, I would do it with profitability, and I think I would have to do the same in Scala ... except that I get a strange error.

In the line "yield t" I get "Illegal start of the statement".

  def dateRange(from : DateTime, to : DateTime, step : TimeSpan) =
  {
      // not sure what the list'y way of doing this is
    var t = from

    while(t < to)
    {
      yield t; // error: illegal start of statement
      t = t + step
    }
  }

Looking at this code, I am interested in 2 things: 1) what did I do wrong? 2) code written very strongly (uses var t, etc.). What is a more functional way to do this in Scala, which is fast enough?

Thank!

+5
3
def dateRange(from : DateTime, to : DateTime, step : TimeSpan): Iterator[DateTime] =
  Iterator.iterate(from)(_ + step).takeWhile(_ <= to)
+17

@Debilski Joda:

import org.joda.time.{DateTime, Period}

def dateRange(from: DateTime, to: DateTime, step: Period): Iterator[DateTime] =
  Iterator.iterate(from)(_.plus(step)).takeWhile(!_.isAfter(to))
+3

In Scala, yieldis a special for for-loops statement.

I don't know C #, but from what I understand, I find it easiest to use, collection.immutable.NumericRange.Exclusive[DateTime]or collection.immutable.NumericRange.Inclusive[DateTime]depending on whether your interval is exclusive or on.

To do this, you need to create an instance Integral[DateTime]that defines arithmetic for the type DateTime.

0
source

All Articles