Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define a function with tuples

Tags:

scala

How can I define a function that is accepting all the tuples(1 to 22) as argument, I have something as follows in mind:

def foo (v=Tuple) =...

foo((1,2))
foo((1,2,3))

EDIT:

To answer the comment: I am actually trying to create a Tensor class which is a set of values and a set of indices. The indices can be covariant and/or contravariant (cf Wikipedia1 and Wikipedia2). I wanted to have a special syntax like Tensor((1,2),(3,4),values) which would create a tensor with values, two covariant indices having length (2,3) and two contravariant indices with length (3,4). So using this syntax I could also write Tensor((1,2,3),3,values) (with an implicit Int=>Tuple1).

I agree that Tuples are not suitable for this, better to use Lists. However the syntax is not so nice then...

like image 457
teucer Avatar asked Sep 11 '26 04:09

teucer


2 Answers

This really isn't what tuples are for (cf. the comments and answers here). Tuples are for doing things like returning multiple values from a method, where in Java you would have to create a lightweight class. If you have an arbitrary number of elements, you should use a collection.

like image 120
Rachel Shallit Avatar answered Sep 13 '26 18:09

Rachel Shallit


Another way to provide a convenient API to your users (aside from implicit conversion) is to use multiple parameter lists with varargs:

def tensor(cov: Int*)(contrav: Int*)(values: Int*) = // ...

Your examples would be written

tensor(1,2)(3,4)(values)
tensor(1,2,3)(3)(values)
like image 30
Aaron Novstrup Avatar answered Sep 13 '26 19:09

Aaron Novstrup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!