on master help sign in
Add sortBy function.
commitbeeaa38755d3da02d8d7e87cacd480d526dc868b authorMax Goldstein <maxgoldstein1@gmail.com> dateThu 7 Nov 2013, 18:59 (13 years ago) parent03256bc
2 files changed+14−1
libraries/List.elm+5−1 libraries/Native/List.js+9
libraries/List.elm+5−1
@@ -22,7 +22,7 @@ list must have the same type.
2222@docs sum, product, maximum, minimum, all, any, and, or
2323
2424# Sorting
25−@docs sort
25+@docs sort, sortBy
2626-}
2727
2828import open Basics
@@ -231,3 +231,7 @@ repeat = Native.List.repeat
231231{-| Sort a list in ascending order. -}
232232sort : [comparable] -> [comparable]
233233sort = Native.List.sort
234+
235+{-| Sort a list by a given comparison function. -}
236+sortBy : (a -> comparable) -> [a] -> [a]
237+sortBy = Native.List.sortBy
libraries/Native/List.js+9
@@ -220,6 +220,14 @@ Elm.Native.List.make = function(elm) {
220220 return fromArray(toArray(xs).sort(cmp));
221221 }
222222
223+ function sortBy(f, xs) {
224+ function cmp(a,b) {
225+ var ord = Utils.compare(f(a))(f(b)).ctor;
226+ return ord === 'EQ' ? 0 : ord === 'LT' ? -1 : 1;
227+ }
228+ return fromArray(toArray(xs).sort(cmp));
229+ }
230+
223231 function nth(xs, n) {
224232 return toArray(xs)[n];
225233 }
@@ -298,6 +306,7 @@ Elm.Native.List.make = function(elm) {
298306 zipWith:F3(zipWith),
299307 zip:F2(zip),
300308 sort:sort,
309+ sortBy:F2(sortBy),
301310 nth:F2(nth),
302311 take:F2(take),
303312 drop:F2(drop),