jgauth
jgauth

Reputation: 315

Sorting by alphabetical order

I would like to create a function which will add a registration number plus a certain negative time. Here is an example :

# enter_car "DEF456" (−4) [("ABC13", −2); ("GHI789", −3)];;
− : (string∗int) list = [("ABC13", −2); ("DEF456" , −4); ("GHI789", −3)]

I am pretty sure I am able to add ("DEF456", -4) to the list. The problem is the list has to be sorted by alphabetical order. How can I sort the list in alphabetical order according to the registration number?

Upvotes: 0

Views: 1040

Answers (2)

jgauth
jgauth

Reputation: 315

This function works perfectly!

let enter_car registration_num time current_list = 
  let new_list = (registration_num, time)::current_list in 
  sort (fun (x, _) (y, _) -> String.compare x y) new_list

Upvotes: 0

Chris
Chris

Reputation: 36620

What you almost certainly actually want in a situation like this is a map. Since they are based on a balanced binary search tree, insertion guarantees ordering will be preserved. The type of list you are looking for can be obtained from such a tree with bindings.

# let cars = StringMap.of_list [("ABC13", -2); ("GHI789", -3)];;
val cars : int StringMap.t = <abstr>
# StringMap.bindings cars;;
- : (string * int) list = [("ABC13", -2); ("GHI789", -3)]
# cars 
  |> StringMap.add "DEF456" ~-4 
  |> StringMap.bindings;;
- : (string * int) list = [("ABC13", -2); ("DEF456", -4); ("GHI789", -3)]

Upvotes: 0

Related Questions