syenmesh
syenmesh

Reputation: 85

Scala generics: Numeric

I have the following Java code:

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class NumTest {

    public static void main(String[] args) {
        final List<Integer> list1 = Arrays.asList(1, 2);
        final List<Float> list2 = Arrays.asList(3.0f, 4.0f);
        final List<Double> list3 = Arrays.asList(5.0, 6.0);
        assertCloseEnough(list1, Arrays.asList(1.0, 2.0));
        assertCloseEnough(list2, Arrays.asList(3.0, 4.0));
        assertCloseEnough(list3, Arrays.asList(5.0, 6.0));
    }

    private static void assertCloseEnough(List<? extends Number> actuals, List<? extends Number> expecteds) {
        assert actuals.size() == expecteds.size();
        for(int i = 0; i < actuals.size(); i++) {
            System.err.println(actuals.get(i).doubleValue());
            assert Math.abs(actuals.get(i).doubleValue() - expecteds.get(i).doubleValue()) < 1E-10;
        }
    }
}

This works as expected, as you can verify with javac NumTest.java && java NumTest.

My question is: how do I write the equivalent in Scala?

The most straightforward approach:

import Numeric.Implicits._

object TestNum extends App {

  assertCloseEnough(Seq(1,2), Seq(1.0, 2.0))
  assertCloseEnough(Seq(3.0f,4.0f), Seq(3.0, 4.0))
  assertCloseEnough(Seq(5.0,6.0), Seq(5.0, 6.0))

  def assertCloseEnough[N: Numeric](actuals: Seq[N], expecteds: Seq[N]): Unit = {
    assert(actuals.size == expecteds.size)
    val ad = actuals.map(implicitly[Numeric[N]].toDouble(_))
    val ed = expecteds.map(implicitly[Numeric[N]].toDouble(_))
    for (i <- expecteds.indices) {
      assert(Math.abs(ad(i) - ed(i)) < 1E-10)
    }
  }
}

Doesn't work:

TestNum1.scala:5: error: could not find implicit value for evidence parameter of type Numeric[AnyVal]
  assertCloseEnough(Seq(1,2), Seq(1.0, 2.0))
                   ^

A slightly more advanced version:

import Numeric.Implicits._

object TestNum extends App {

  assertCloseEnough(Seq[Int](1,2), Seq[Double](1.0, 2.0))
  assertCloseEnough(Seq[Float](3.0f,4.0f), Seq[Double](3.0, 4.0))
  assertCloseEnough(Seq[Double](5.0,6.0), Seq[Double](5.0, 6.0))

  def assertCloseEnough[N: Numeric](actuals: Seq[N], expecteds: Seq[N]): Unit = {
    assert(actuals.size == expecteds.size)
    val ad = actuals.map(implicitly[Numeric[N]].toDouble(_))
    val ed = expecteds.map(implicitly[Numeric[N]].toDouble(_))
    for (i <- expecteds.indices) {
      assert(Math.abs(ad(i) - ed(i)) < 1E-10)
    }
  }
}

Also doesn't work, with the same error.

Looking at other questions here such as Scala Generics and Numeric Implicits I came up with the following:

import Numeric.Implicits._

object TestNum extends App {

  assertCloseEnough(Seq(1,2), Seq(1.0, 2.0))
  assertCloseEnough(Seq(3.0f,4.0f), Seq(3.0, 4.0))
  assertCloseEnough(Seq(5.0,6.0), Seq(5.0, 6.0))

  def assertCloseEnough[N: Numeric, T1 <% N, T2 <% N](actuals: Seq[T1], expecteds: Seq[T2]): Unit = {
    assert(actuals.size == expecteds.size)
    val ad = actuals.map(implicitly[Numeric[T1]].toDouble(_))
    val ed = expecteds.map(implicitly[Numeric[T2]].toDouble(_))
    for (i <- expecteds.indices) {
      assert(Math.abs(ad(i) - ed(i)) < 1E-10)
    }
  }
}

Which also doesn't work:

TestNum3.scala:5: error: ambiguous implicit values:
 both object BigIntIsIntegral in object Numeric of type scala.math.Numeric.BigIntIsIntegral.type
 and object IntIsIntegral in object Numeric of type scala.math.Numeric.IntIsIntegral.type
 match expected type Numeric[N]
  assertCloseEnough(Seq(1,2), Seq(1.0, 2.0))
                   ^

What am I missing here? How can I get this to work?

Upvotes: 2

Views: 670

Answers (2)

Dima
Dima

Reputation: 40500

Your sequences have elements of two different types, but you are trying to parametrize it as one. Something like this should work:

 def assertCloseEnough[N1, N2](expected: Seq[N1], actual: Seq[N2])(implicit e1: Numeric[N1], e2: Numeric[N2]) {
    assert(
      expected.size == actual.size &&
      (expected zip actual).forall { case (a,b) => 
         math.abs(e1.toDouble(a)-e2.toDouble(b)) < 1e-10
      }
   )
 }

This declaration is equivalent to closeEnough[N1 : Numeric, N2 : Numeric]( ...) but it is a little more convenient in this case, because it gives actual names to the "evidence" implicits, so that you don't have to fish them out using implicitly[Numeric[N1]] ...

Also, don't use foo(i) with Seq this is almost always a bad idea. If you are sure you need random access (most of the time, you don't), use IndexedSeq instead.

Upvotes: 4

Tom
Tom

Reputation: 2254

You need to use two types (e.g. T1 and T2), and provide implicit arguments to your method or summon a Numeric from implicit scope with implicitly

Two ways to do it below:

def assertCloseEnough[T1: Numeric, T2: Numeric](actuals: Seq[T1], expecteds: Seq[T2]): Unit = {
  assert(actuals.size == expecteds.size)
  val ad = actuals.map(implicitly[Numeric[T1]].toDouble)
  val ed = expecteds.map(implicitly[Numeric[T2]].toDouble)
  for (i <- expecteds.indices) {
    assert(Math.abs(ad(i) - ed(i)) < 1E-10)
  }
}

def assertCloseEnough[T1, T2](actuals: Seq[T1], expecteds: Seq[T2])(implicit t1: Numeric[T1], t2: Numeric[T2]): Unit = {
  assert(actuals.size == expecteds.size)
  val ad = actuals.map(_.toDouble)
  val ed = expecteds.map(_.toDouble)
  for (i <- expecteds.indices) {
    assert(Math.abs(ad(i) - ed(i)) < 1E-10)
  }
}

Upvotes: 1

Related Questions