questionersam
questionersam

Reputation: 1125

Returning tuple with variable number of elements

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?

Upvotes: 5

Views: 2235

Answers (3)

Channing Walton
Channing Walton

Reputation: 4007

You might consider using HLists instead from Miles Sabin's Shapeless library. They also support conversion to and from tuples.

Upvotes: 1

Tesseract
Tesseract

Reputation: 8139

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)

Upvotes: 3

Luigi Plinge
Luigi Plinge

Reputation: 51109

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
}

Upvotes: 3

Related Questions