on master help sign in
Merge pull request #355 from mgold/sort
ccf737eEvan Czaplicki
libraries/List.elm+16
@@ -20,6 +20,9 @@ list must have the same type.
20
20
21# Special Folds
21# Special Folds
22@docs sum, product, maximum, minimum, all, any, and, or
22@docs sum, product, maximum, minimum, all, any, and, or
23+
24+# Sorting
25+@docs sort, sortBy, sortWith
23-}
26-}
24
27
25import open Basics
28import open Basics
@@ -224,3 +227,16 @@ drop = Native.List.drop
224-}
227-}
225repeat : Int -> a -> [a]
228repeat : Int -> a -> [a]
226repeat = Native.List.repeat
229repeat = 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) {
220 }
220 }
221
221
222 function sort(xs) {
222 function sort(xs) {
223+ return fromArray(toArray(xs).sort(Utils.cmp));
224+ }
225+
223− function cmp(a,b) {
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){
224− var ord = Utils.compare(a,b).ctor;
234+ var ord = f(a)(b).ctor;
225− return ord=== 'EQ' ? 0 : ord === 'LT' ? -1 : 1;
235+ return ord === 'EQ' ? 0 : ord === 'LT' ? -1 : 1;
226− }
236+ }));
227− return fromArray(toArray(xs).sort(cmp));
228 }
237 }
229
238
230 function nth(xs, n) {
239 function nth(xs, n) {
@@ -312,6 +321,8 @@ Elm.Native.List.make = function(elm) {
312 zipWith:F3(zipWith),
321 zipWith:F3(zipWith),
313 zip:F2(zip),
322 zip:F2(zip),
314 sort:sort,
323 sort:sort,
324+ sortBy:F2(sortBy),
325+ sortWith:F2(sortWith),
315 nth:F2(nth),
326 nth:F2(nth),
316 take:F2(take),
327 take:F2(take),
317 drop:F2(drop),
328 drop:F2(drop),