How to write a method that is common to any number (Order [_]) in scala?

I am trying to implement a simple method that can be applied to any number:

/** * Round `candidate` to the nearest `bucket` value. */ def bucketise[Ordering[A]](buckets: Seq[Ordering[A]], candidate: Ordering[A]): Ordering[A] = ??? 

I do not want to simply parameterize completely as a whole, since my method will use comparison <and>. I think this means that I should limit any type of Ordering[_] , but I seem to be unable to specify this.

Calling the above (or the option where I replace A with _ ) causes the following error:

 error: type mismatch; found : Int(3) required: Ordering[_] NumberUtils.bucketise(List(1,2,3), 3) 

What is the correct syntax for what I'm trying to achieve?

0
source share
1 answer

If I do not understand what you want:

 def bucketise[A](buckets: Seq[A], candidate: A)(implicit ev: Ordering[A]): A = ??? 

which can be written in candied form:

 def bucketise[A : Ordering](buckets: Seq[A], candidate: A): A = ??? 
+4
source

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


All Articles