Skip to content
This repository was archived by the owner on Aug 16, 2024. It is now read-only.

Commit 3721ed8

Browse files
hdgarroodJoelQ
authored andcommitted
TIL sorting in reverse order in Haskell
1 parent b820c86 commit 3721ed8

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

haskell/sorting-in-reverse-order.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Sorting in reverse order
2+
3+
`Data.Ord` contains a newtype, `Down`, which can wrap any type that has an
4+
`Ord` instance, in order to provide a reversed `Ord` instance for that type.
5+
6+
For example:
7+
8+
```hs
9+
Prelude> import Data.Ord (Down(..))
10+
Prelude Data.Ord> :info Down
11+
newtype Down a = Down a -- Defined in ‘Data.Ord’
12+
instance Ord a => Ord (Down a) -- Defined in ‘Data.Ord’
13+
Prelude Data.Ord> Down 3 > Down 4
14+
True
15+
```
16+
17+
This can be very convenient for reversing sort order:
18+
19+
```hs
20+
Prelude> import Data.Ord (Down(..), comparing)
21+
Prelude Data.Ord> import Data.List (sortBy)
22+
Prelude Data.Ord Data.List> sortBy (comparing Down) [1..10]
23+
[10,9,8,7,6,5,4,3,2,1]
24+
```

0 commit comments

Comments
 (0)