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?
Numeric(which is a typeclas). - BTW, you may want to use aListand prepend (with areversein the end) or use aVector; since that code can be extremely inefficient. - PS: The stdlib already has such functionality in cases you didn't know; but I guess this is just an exercise to learn the language.List.range- Well, actually you can replaceListwith any collection.