ocaml

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?


Solution

  • 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