0

Hi I am trying to define a generic function isNonNeg that makes use of an arithmetic operator as follows:

scala> def isNonNeg[A](a:A): Boolean = { if (a >= 0.0) true else false}

However this produces the following error:

<console>:13: error: value >= is not a member of type parameter A
   def isNonNeg[A](a:A): Boolean = { if (a >= 0.0) true else false}
                                           ^

I'm assuming that the problem is because type A is unknown. Is there a way of specifying that A should be a numeric type hence >= is a valid operator. Would some sort of type class or implicit parameter offer a solution ?

1 Answer 1

2

You can use the Numeric typeclass: http://www.scala-lang.org/api/2.11.8/#scala.math.Numeric

def isNonNeg [A](a: A)(implicit ev: Numeric[A]) = ev.gteq(a, ev.zero)

If you want to use the operator, you can import Ordering.Implicits:

import Ordering.Implicits._
def isNonNeg [A](a: A)(implicit ev: Numeric[A]) = a >= ev.zero
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.