I have a need to generate a sequence of elements of a certain Numeric type with a certain start and end and with the given increment. Here is what I came up with:
import java.text.DecimalFormat
def round(elem: Double): Double = {
val df2 = new DecimalFormat("###.##")
df2.format(elem).toDouble
}
def arrange(start: Double, end: Double, increment: Double): Seq[Double] = {
@scala.annotation.tailrec
def recurse(acc: Seq[Double], start: Double, end: Double): Seq[Double] = {
if (start >= end) acc
else recurse(acc : round(start increment), round(start increment), end)
}
recurse(Seq.empty[Double], start, end)
}
arrange(0.0, 0.55, 0.05) foreach println
This works as expected and gives me the following result:
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
However, I would like to see if I can make this generic so that the same function works for an Int, Long, Float. Is there a way to simplify this?
CodePudding user response:
Came across this much simpler version:
@ BigDecimal(0.0) to BigDecimal(0.5) by BigDecimal(0.05)
res23: collection.immutable.NumericRange.Inclusive[BigDecimal] = NumericRange(0.0, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50)