Skip to content

Instantly share code, notes, and snippets.

@xpe
Last active January 11, 2026 22:13
Show Gist options
  • Select an option

  • Save xpe/d28a9b0ed521cf8c2eb9310aff6f128b to your computer and use it in GitHub Desktop.

Select an option

Save xpe/d28a9b0ed521cf8c2eb9310aff6f128b to your computer and use it in GitHub Desktop.
A quick tour of building `argsort` with Nushell... enjoy!

You can define commands (like functions) like this (in the shell if you want for easy trial and error):

# Returns indices that would sort the input list
def argsort [--reverse (-r)]: list<number> -> list<int> {
    enumerate | sort-by item --reverse=$reverse | get index
}

Then you get nice help like this "for free":

> help argsort
Returns indices that would sort the input list

Usage:
  > argsort {flags}

Flags:
  -h, --help: Display the help message for this command
  -r, --reverse

Input/output types:
  ╭───┬──────────────┬───────────╮
  │ # │    input     │  output   │
  ├───┼──────────────┼───────────┤
  │ 0 │ list<number> │ list<int> │
  ╰───┴──────────────┴───────────╯

This shows it in action... Nushell leans heavily on pipelines:

[2.2 4.4 5.5 1.1 3.3] | argsort
╭───┬───╮
│ 0 │ 3 │
│ 1 │ 0 │
│ 2 │ 4 │
│ 3 │ 1 │
│ 4 │ 2 │
╰───┴───╯
[2.2 4.4 5.5 1.1 3.3] | argsort -r
╭───┬───╮
│ 0 │ 2 │
│ 1 │ 1 │
│ 2 │ 4 │
│ 3 │ 0 │
│ 4 │ 3 │
╰───┴───╯

I used floats just because you can. Other shells like Bash and Zsh do floats either via workarounds or with extra syntax, but neither treat floats as first-class values.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment