query
On this page

sortOn

lib.lists.sortOn

Docs pulled from | This Revision | about 2 hours ago


Sort a list based on the default comparison of a derived property b.

The items are returned in b-increasing order.

Performance:

The passed function f is only evaluated once per item, unlike an unprepared sort using f p < f q.

Laws:

sortOn f == sort (p: q: f p < f q)

Inputs

f

1. Function argument

list

2. Function argument

Type

sortOn :: (a -> b) -> [a] -> [a], for comparable b

Examples

lib.lists.sortOn usage example

sortOn stringLength [ "aa" "b" "cccc" ]
=> [ "b" "aa" "cccc" ]

Noogle detected

Aliases

Implementation

The following is the current implementation of this function.

sortOn = f: list:
    let
      # Heterogenous list as pair may be ugly, but requires minimal allocations.
      pairs = map (x: [(f x) x]) list;
    in
      map
        (x: builtins.elemAt x 1)
        (sort
          # Compare the first element of the pairs
          # Do not factor out the `<`, to avoid calls in hot code; duplicate instead.
          (a: b: head a < head b)
          pairs);