How can sort a [MVar a] list? using a as the element to compare in the sort. E.g:
sortList :: [MVar Int] -> [MVar Int]
I cannot think a ways without breaking other threads.
Update:
I need to sort the list, because I want to implement a reference count like MVar and return always the one with least references. Something like:
getLeastUsed :: [MVar Int] -> MVar Int
getLeastUsed = head . sortList
And in the thread I want to increase the ‘Int’.
Update:
I was notice by answers that the rigth signature need IO because MVar
First of all, your type signature is impossible; reading an
MVaris not referentially transparent (as should hopefully be obvious–that’s what they’re for!). This has two consequences:IOactionMVarwas read; not only may it be invalid by the time you use the list, it may change halfway through such that the first value is out of date before you read the last value.The former is unavoidable, and assuming the latter is acceptable for your purposes, you can do essentially what @hammar demonstrated.
However, given that the sorting will be quickly out of date, and that you seem to be mostly interested in the least element, you might find something like this more directly useful since there’s little use to sorting otherwise: