I'm experimenting writing a percentile utility in Scala. I was thinking of writing a class that is initialized with a variable number of Int
parameters. For example, a Percentile
class initialized with 50,95
means it can compute the 50th percentile and the 95th percentile. The class would roughly look like this:
class PercentileUtil(num: Int*) {
def collect(value: Int) {
// Adds to a list
}
def compute = {
// Returns the 50th and 95th percentiles as a tuple
}
}
How should I define the function compute?
I'd return a Map if I were you:
class PercentileUtil(percentiles: Int*) {
private def nthPercentile[T](n: Int, xs: Seq[T]): Seq[T] = ...
def compute[T](xs: Seq[T]) = percentiles.map(p => p -> nthPercentile(p, xs)).toMap
}
If it has to be a Tuple you can declare the return value to be a Product.
def compute: Product = if(...) (1,2) else ("1", "2", "3")
compute match {
case (a: Int, b: Int) =>
case (a: String, b: String, c: String) =>
}
compute.productIterator.foreach(println)
You might consider using HLists instead from Miles Sabin's Shapeless library. They also support conversion to and from tuples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With