Skip to content

Commit 43d3690

Browse files
authored
Merge pull request #97 from negator/master
Haskell inspired sortWith
2 parents 1e56c03 + 45ef98a commit 43d3690

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

src/Data/Array.purs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ module Data.Array
7575

7676
, sort
7777
, sortBy
78-
78+
, sortWith
7979
, slice
8080
, take
8181
, takeWhile
@@ -469,6 +469,11 @@ sortBy comp xs = sortImpl comp' xs
469469
EQ -> 0
470470
LT -> -1
471471

472+
-- | Sort the elements of an array in increasing order, where elements are
473+
-- | sorted based on a projection
474+
sortWith :: forall a b. Ord b => (a -> b) -> Array a -> Array a
475+
sortWith f = sortBy (comparing f)
476+
472477
foreign import sortImpl :: forall a. (a -> a -> Int) -> Array a -> Array a
473478

474479
--------------------------------------------------------------------------------

test/Test/Data/Array.purs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,9 @@ testArray = do
228228
log "sortBy should reorder a list into ascending order based on the result of a comparison function"
229229
assert $ A.sortBy (flip compare) [1, 3, 2, 5, 6, 4] == [6, 5, 4, 3, 2, 1]
230230

231+
log "sortWith should reorder a list into ascending order based on the result of compare over a projection"
232+
assert $ A.sortWith id [1, 3, 2, 5, 6, 4] == [1, 2, 3, 4, 5, 6]
233+
231234
log "take should keep the specified number of items from the front of an array, discarding the rest"
232235
assert $ (A.take 1 [1, 2, 3]) == [1]
233236
assert $ (A.take 2 [1, 2, 3]) == [1, 2]

0 commit comments

Comments
 (0)