Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning tuple with variable number of elements

Tags:

tuples

scala

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?

like image 353
questionersam Avatar asked Jul 13 '12 18:07

questionersam


3 Answers

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
}
like image 131
Luigi Plinge Avatar answered Oct 16 '22 08:10

Luigi Plinge


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)
like image 36
SpiderPig Avatar answered Oct 16 '22 09:10

SpiderPig


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

like image 1
Channing Walton Avatar answered Oct 16 '22 09:10

Channing Walton