on master help sign in
Merge pull request #355 from mgold/sort

Add sorting (targeting dev)

commitccf737e9992baa9f8b0b4cf70414ca39c1a49e12 authorEvan Czaplicki <info@elm-lang.org> dateSun 8 Dec 2013, 15:18 (13 years ago) parent47c6cbcbbdc676
2 files changed+32−5
libraries/List.elm+16 libraries/Native/List.js+16−5
libraries/List.elm+16
@@ -20,6 +20,9 @@ list must have the same type.
2020
2121# Special Folds
2222@docs sum, product, maximum, minimum, all, any, and, or
23+
24+# Sorting
25+@docs sort, sortBy, sortWith
2326-}
2427
2528import open Basics
@@ -224,3 +227,16 @@ drop = Native.List.drop
224227-}
225228repeat : Int -> a -> [a]
226229repeat = Native.List.repeat
230+
231+{-| Sort a list in ascending order. -}
232+sort : [comparable] -> [comparable]
233+sort = Native.List.sort
234+
235+{-| Sort a list by a given comparison transformation, such a [record field
236+accessors](http://elm-lang.org/learn/Syntax.elm#records). -}
237+sortBy : (a -> comparable) -> [a] -> [a]
238+sortBy = Native.List.sortBy
239+
240+{-| Sort a list by a given comparison function. -}
241+sortWith : (a -> a -> Order) -> [a] -> [a]
242+sortWith = Native.List.sortWith
libraries/Native/List.js+16−5
@@ -220,11 +220,20 @@ Elm.Native.List.make = function(elm) {
220220 }
221221
222222 function sort(xs) {
223− function cmp(a,b) {
224− var ord = Utils.compare(a,b).ctor;
225− return ord=== 'EQ' ? 0 : ord === 'LT' ? -1 : 1;
226− }
227− return fromArray(toArray(xs).sort(cmp));
223+ return fromArray(toArray(xs).sort(Utils.cmp));
224+ }
225+
226+ function sortBy(f, xs) {
227+ return fromArray(toArray(xs).sort(function(a,b){
228+ return Utils.cmp(f(a), f(b));
229+ }));
230+ }
231+
232+ function sortWith(f, xs) {
233+ return fromArray(toArray(xs).sort(function(a,b){
234+ var ord = f(a)(b).ctor;
235+ return ord === 'EQ' ? 0 : ord === 'LT' ? -1 : 1;
236+ }));
228237 }
229238
230239 function nth(xs, n) {
@@ -312,6 +321,8 @@ Elm.Native.List.make = function(elm) {
312321 zipWith:F3(zipWith),
313322 zip:F2(zip),
314323 sort:sort,
324+ sortBy:F2(sortBy),
325+ sortWith:F2(sortWith),
315326 nth:F2(nth),
316327 take:F2(take),
317328 drop:F2(drop),