diff options
author | Hans Raaf <hara@oderwat.de> | 2015-03-11 22:17:49 +0100 |
---|---|---|
committer | Hans Raaf <hara@oderwat.de> | 2015-03-11 22:22:58 +0100 |
commit | 06ea53e6920c561eb3ad27bfcbd57aba608b1bac (patch) | |
tree | 02aba91d8b99f50b3d47fa3330d0ee8c76cd11a2 | |
parent | 1a98de87122dafd483dcc402f528633f63bf4508 (diff) | |
download | Nim-06ea53e6920c561eb3ad27bfcbd57aba608b1bac.tar.gz |
Better documentation and rename of sortByIt().
-rw-r--r-- | lib/pure/algorithm.nim | 21 |
1 files changed, 17 insertions, 4 deletions
diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index 05fcc9584..08d224dfd 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -196,7 +196,7 @@ proc sorted*[T](a: openArray[T], cmp: proc(x, y: T): int {.closure.}, result[i] = a[i] sort(result, cmp, order) -template sortByIt*(seq1, op: expr): expr = +template sortedByIt*(seq1, op: expr): expr = ## Convenience template around the ``sorted`` proc to reduce typing. ## ## The template injects the ``it`` variable which you can use directly in an @@ -204,10 +204,23 @@ template sortByIt*(seq1, op: expr): expr = ## ## .. code-block:: nim ## - ## var users: seq[tuple[id: int, name: string]] = - ## @[(0, "Smith"), (1, "Pratt"), (2, "Sparrow")] + ## type Person = tuple[name: string, age: int] + ## var + ## p1: Person = (name: "p1", age: 60) + ## p2: Person = (name: "p2", age: 20) + ## p3: Person = (name: "p3", age: 30) + ## p4: Person = (name: "p4", age: 30) ## - ## echo users.sortByIt(it.name) + ## people = @[p1,p2,p4,p3] + ## + ## echo people.sortedByIt(it.name) + ## + ## Because the underlying ``cmp()`` is defined for tuples you can do + ## a nested sort like in the following example: + ## + ## .. code-block:: nim + ## + ## echo people.sortedByIt((it.age, it.name)) ## var result {.gensym.} = sorted(seq1, proc(x, y: type(seq1[0])): int = var it {.inject.} = x |