Skip to content

Instantly share code, notes, and snippets.

@AlexRogalskiy
Last active December 19, 2020 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexRogalskiy/8ce0961daecd2c541d0078e42dc5fce8 to your computer and use it in GitHub Desktop.
Save AlexRogalskiy/8ce0961daecd2c541d0078e42dc5fce8 to your computer and use it in GitHub Desktop.
Scala monoid range
object MonoidRange {
case class MonoidRangeBuilder[T](from: T, to: T, incl: Boolean)(implicit mo: Monoid[T], ordering: Ordering[T]) {
def by(step: T) = Stream.iterate(from) { previous: T =>
previous + step
}.takeWhile { x =>
if (incl) {
ordering.lteq(x, to)
} else {
ordering.lt(x, to)
}
}
}
implicit class RichMonoidRange[T](wrap: T)(implicit mo: Monoid[T], ordering: Ordering[T]) {
def until(incl: T) = MonoidRangeBuilder(wrap, incl, false)
def to(incl: T) = MonoidRangeBuilder(wrap, incl, true)
}
}
until: IndexedSeq[com.twitter.util.Duration] =
Vector(10.seconds, 12.seconds, 14.seconds, 16.seconds, 18.seconds)
to: IndexedSeq[com.twitter.util.Duration] =
Vector(10.seconds, 12.seconds, 14.seconds, 16.seconds, 18.seconds, 20.seconds)
import MonoidRange._
import com.twitter.util.Duration
import java.util.concurrent.TimeUnit
implicit val durationMondoid = new Monoid[Duration] {
override def zero: Duration = Duration(0, TimeUnit.SECONDS)
override def plus(l: Duration, r: Duration): Duration = {
l + r
}
}
import com.twitter.conversions.time._
val until = 10.seconds until 20.seconds by 2.seconds toIndexedSeq
val to = 10.seconds to 20.seconds by 2.seconds toIndexedSeq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment