scala - Generics not so generic ! -


I tried to apply a normal binary search algorithm in Scala. Here it is:

  type orde = {def < (X: Any): Boolean def & gt; (X: Any): Boolean} DEF bin search [T & LT: ORD] (X: T, start: int, and: int, T: array [T]: boolean = {if (start; end) returned False wal pause = (start + end) / 2 if (t (pause) == x) and if (t (pause)  
  binSearch (3,0,4, Aare (1,2,5,6))  

compiler showing this That IR is not a member of the order, but as I know that class IT has and & gt; ways to solve this strange problem What will I do? Thanks

The easiest is to use Scala's standard library command [T] ] attribute and an intense example with it

using a visible bound <% [t] , Scala is an underlying command [radius] Within the scope of Not appear and will allow it in any way (such as & lt; , & gt; , & gt; = , & lt; = to use, compare on the common type).

T]): int = {Diff Search in the middle (start: int, end: IT): int = {if (start> end) return -1 / / not found Val pos = (start + end) / 2 (Xs (pause) == x) POS / GET, then return the second position (xs (pos) & lt; x) SearchBitini (position + 1, end) and search between (start, position -1)} search Between (0, xs.length)}

Then you can immediately find it in many common sections such as That byte , small , int , long , string , BigInt , ... basically for any type, even by implementing the Scale de Efining a command [t] example, or order [yourType] Provide and then either explicitly send it to binarySearch () .

Here are examples with int and string :

  Scala> Binary search (2, sac (1,2,3,4,5)) res1: int = 1 scale & gt; Binary search ("D", sec ("A", "B", "D", "F")) res2: Int = 2  

Comments