0

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?

3
  • 1
    Yup use Numeric (which is a typeclas). - BTW, you may want to use a List and prepend (with a reverse in the end) or use a Vector; 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. Commented Nov 12, 2021 at 19:57
  • Which function is that? Commented Nov 12, 2021 at 20:00
  • 2
    List.range - Well, actually you can replace List with any collection. Commented Nov 12, 2021 at 20:12

1 Answer 1

5

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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.