0
votes
Datatype events = enter of string * real | exit of string *real; 

So i have this Datatype and i have to write a function that takes a list of events as input and return that list sorted by the real part of events. I tried to write some functions but didnt come up with anything good, any ideas?

this is the code i tried:

val rec ordina = fn 
     [] => []
    |v1::v2::l => if (#2(v2)) > (#2(v1)) 
                  then ordina (v1::l)
                  else oridna (v2::1);

Errors i got:

poly: error: Can't find a fixed record type. Found near #2

poly: error: Can't find a fixed record type. Found near #2

1
What functions did you try to write? What errors did you encounter? If you want help on homework then you should show your efforts. - John Coleman
i posted the code i tried to use. - Petar Zurzevic
The #2 macro works on tuples, but Enter (s, r) and Exit (s, r) are not directly tuples. You should make a getter function like I suggest in my answer below. Whether you use pattern matching entirely, like I suggest, or you write fun get_... (Enter pair) = #2 pair | ... are both options. - sshine

1 Answers

1
votes

Some feedback,

  • The datatype declaration should probably be

    datatype event = Enter of string * real
                   | Exit of string * real
    

    A single value contains a single event.

    The plural is achieved by having a value of e.g. type event list.

    Value constructors are usually written with an uppercase start letter.

  • In SML/NJ you have a generic sort function called ListMergeSort.sort. It takes a function with the type 'a * 'a -> bool where 'a = event in this case. You could then write a function,

    fun cmp_event (event_a, event_b) = ...
    

    that returns whether event_a should be ordered before event_b based on their real parts. Hint: First, make a helper function that extracts the real part. (Come up with a better name that reflects the purpose of the real part.)

    fun get_real_part (Enter (_, r)) = ...
      | get_real_part ... = ...
    
  • If you're not allowed to use ListMergeSort.sort, then make your own sort.