Massive languages ​​like code reuse in Scala

Array programming languages (also known as vector or multidimensional languages) generalize scalar operations so that they are transparently applied to vectors, matrices, and higher dimensional arrays.

Is it possible to reuse this type in Scala?

+3
source share
3 answers

It is quite possible (I did it myself) with the corresponding implications, although the result is not always as simple as a language that was designed from scratch in this way.

, , . - Scala , + . ( , * , - , !)

class ArraysAdd(a: Array[Int]) {
  def +(i: Int) = a.map(_ + i)
  def +(b: Array[Int]) = {
    if (b.length==a.length) (a,b).zipped.map(_ + _).toArray
    else throw new IllegalArgumentException
  }
}
class ScalarAddsToArray(i: Int) {
  def +(a: Array[Int]) = a.map(_ + i)
}
implicit def array2addable(a: Array[Int]) = new ArraysAdd(a)
implicit def scalar2arrayaddable(i: Int) = new ScalarAddsToArray(i)

:

scala> Array(1,2,3) + 5
res2: Array[Int] = Array(6, 7, 8)

scala> Array(1,7) + Array(3,2)
res3: Array[Int] = Array(4, 9)

scala> 4 + Array(-2,-3,-1)
res4: Array[Int] = Array(2, 1, 3)

, ( generics Numeric - , ), "matrix" , , .

. , math.sqrt, a map sqrt sqrt(a), . ; .

, . (Scala - , .)

+5

Scala, , APL J. Scala - , . Scala , , . Scala , ( ), 2- .

, APL/J-ish Scala "map" "flatMap", ( , , ). , Scala, .

+5

Something like scalala what are you looking for?

+5
source

Source: https://habr.com/ru/post/1759442/


All Articles