Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created August 30, 2015 15:03
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Simple insertion into an ordered List
val li=List(1,2,10,20,30) //> li : List[Int] = List(1, 2, 10, 20, 30)
def insert[T](li:List[T],x:T)(implicit cmp:Ordering[T])={
val (first,last)=li.partition {cmp.lteq(_, x) }
first:::x::last
} //> insert: [T](li: List[T], x: T)(implicit cmp: Ordering[T])List[T]
insert(li,11) //> res0: List[Int] = List(1, 2, 10, 11, 20, 30)
insert(li,10) //> res1: List[Int] = List(1, 2, 10, 10, 20, 30)
insert(li,9) //> res2: List[Int] = List(1, 2, 9, 10, 20, 30)
insert(li,0) //> res3: List[Int] = List(0, 1, 2, 10, 20, 30)
insert(li,999) //> res4: List[Int] = List(1, 2, 10, 20, 30, 999)
insert(List('a','b','m','z'),'l') //> res5: List[Char] = List(a, b, l, m, z)
@abbas-taher
Copy link

very nice.
I was writing an imperative version and it looked ugly.
Thanks

@mayonesa
Copy link

unfortunately, partition will not exploit the fact that it is sorted and it can binary-searched into

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment