radumanolescu
radumanolescu

Reputation: 4161

Scala Typeclass for methods with parameters

I have tried to add methods like "multiply by a scalar" to Array[T] via a typeclass, to mimic numpy functionality. I have looked at an example, which works and adds a "show" method with no parameters to Array[T]. However, in my case, I find that I am unable to add methods with parameters, e.g. array.*(2.0).

Using Scala 2.12.6.

How can I make this code work?

package numpy

trait BehaveLikeNumpy[T] {
  def *(a: Array[T], x: T): Array[T]
}

object BehaveLikeNumpyInstances {

  def apply[T](implicit bln: BehaveLikeNumpy[T]): BehaveLikeNumpy[T] = bln

  object ops {
    def *[T: BehaveLikeNumpy](a: Array[T], x: T): Array[T] = BehaveLikeNumpyInstances[T].*(a, x)

    implicit class BehaveLikeNumpyOps[T: BehaveLikeNumpy](a: Array[T]) {
      def *(x: T) = BehaveLikeNumpyInstances[T].*(a, x)
    }
  }

  implicit val arrayTimes_Double = (a: Array[Double], x: Double) => a.map(y => y * x)
}

package some.pkg
import numpy.BehaveLikeNumpyInstances
import numpy.BehaveLikeNumpyInstances.ops._

val aaa: Array[Double] = (0 until 5).toArray.map(_.toDouble)
aaa.show // Works. See https://blog.scalac.io/2017/04/19/typeclasses-in-scala.html
val s1 = aaa.*(2.0)// Error: value * is not a member of Array[Double]
val s2 = aaa * 2.0 // Error: value * is not a member of Array[Double]

Upvotes: 0

Views: 97

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51703

Firstly you lost type (for transformation of lambda to SAM trait)

implicit val arrayTimes_Double: BehaveLikeNumpy[Double] = 
  (a: Array[Double], x: Double) => a.map(y => y * x)

secondly you lost underscore

import numpy.BehaveLikeNumpyInstances._

Upvotes: 2

Related Questions