Array programming languages (also known as vector or multidimensional languages) generalize operations on scalars to apply transparently to vectors, matrices, and higher dimensional arrays.
Is it possible to achieve this kind of code reuse in Scala?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s entirely possible (I’ve done so myself) with appropriate implicits, though the result is not always as utterly seamless as a language that has been designed from the ground up that way.
For example, suppose you want to treat arrays of integers as vectors and want to be able to add them to each other and to scalars. You have to define the operation yourself–Scala can’t guess what
+should mean on an array. (Good thing, too, because*doesn’t usually have the obvious element-by-element meaning on matrices, and it means something else again when it comes to convolution!) You canand then you can do math on arrays of integers:
If you want to cover all data types it gets trickier (you need to use generics and Numeric at least–or write a code generator to cover the cases you need), and for efficiency you might want to create a custom “matrix” class instead of sticking with raw arrays that you keep wrapping with extra functionality.
This covers basic operations. For mathematical functions like
math.sqrt, if you don’t mind typinga map sqrtinstead ofsqrt(a)then you don’t need to do anything. Otherwise, you can overload them all yourself; tedious, but it then lets you use them transparently.Or you could use a library that has already done much of this for you. (Scalala is the best candidate I know of for matrices.)