[Haskell-cafe] What is the best way to preserve the order of a list (RESOLVED)

John Ky newhoggy at gmail.com
Wed Nov 1 23:00:49 EST 2006


Thanks Stefan,

-John

On 11/1/06, Stefan Holdermans <stefan at cs.uu.nl> wrote:
>
> John,
>
> > My question is, how do I preserve the ordering of entities in my
> > list and still be able to assign the proper order values to each
> > entity?  Is there an efficient way to do this?  How else might I
> > improve my orderByPriority algorithm.
>
> Straightforwardly, you could do it like this:
>
>    import List (sortBy)
>
>    type Priority = Int
>    type Order    = Int
>
>    order :: [Priority] -> [(Priority, Order)]
>    order =  unlabel . sortOnLab . assignOrder . sortOnPrio . label
>      where
>        label       = zip [0 ..]
>        unlabel     = map snd
>        sortOnLab   = sortBy (\(l, _) (m, _) -> compare l m)
>        sortOnPrio  = sortBy (\(_, p) (_, q) -> compare p q)
>        assignOrder = \xs -> zipWith (\(l, p) o -> (l, (p, o))) xs [0 ..]
>
> For instance:
>
>    > order [5, 2, 3, 7]
>    [(5,2),(2,0),(3,1),(7,3)]
>
> HTH,
>
>    Stefan
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20061102/92c3e54e/attachment.htm


More information about the Haskell-Cafe mailing list