Scala comparing generics? -
i writing generic binary search implementation , failing compile (compare not member of type parameter b
) though b
ordering
, should converted implicitly ordered
has compare
method:
/** * generic binary search in (min,max) f achieve target goal * o(log n) * * @param f function binary search on - monotonically increasing * @param min starting minimum guess (must exclusive) * @param max starting maximum guess (must exclusive) * @param avg mid function (min+max)/2 * @param goal target achieve * @tparam input type of f * @tparam b output type of f * @return some(x) such f(x) goal else none */ import scala.math.ordering.implicits._ def binarysearch[a: ordering, b: ordering](f: => b, min: a, max: a, avg: (a, a) => a, goal: b): option[a] = { if (min >= max) { none } else { val mid = avg(min, max) f(mid) compare goal match { case 1 => binarysearch(f, min, mid, avg, goal) case -1 => binarysearch(f, mid, max, avg, goal) case 0 => some(mid) } } }
try importing scala.math.ordered
:
import scala.math.ordered._
it has implicit conversion of elements of type b
ordered
granted there ordering
typeclass type b
in scope.
Comments
Post a Comment