-1

if i have a sequence

let my_seq = @[("a", "hello"), ("c", "world"), ("b", "to")]

how can i sort this so that it returns:

let my_seq = @[("a", "hello"), ("b", "to")] ("c", "world")

tried to google it but theres no resources for nim basically

1
  • Re "theres no resources for nim": The best resource is Nim's own documentation. Specifically in your case, the one for the std/algorithm module. Commented Oct 13, 2024 at 22:23

1 Answer 1

3

Use the sort procedure from the standard library. If needed, customize it by also providing a comparison function that defines how the items should be compared to each other, and returns an integer indicating their order.

Simple case:

import std/algorithm

var my_seq = @[("a", "hello"), ("c", "world"), ("b", "to")]

my_seq.sort()

echo(my_seq)

Demo

Example comparing the tuples just by their first element (at position 0):

import std/algorithm

var my_seq = @[("a", "hello"), ("c", "world"), ("b", "to")]

proc myCmp(x, y: (string, string)): int = cmp(x[0], y[0])

my_seq.sort(myCmp)

echo(my_seq)

Demo

Note that I've changed let to var to make the sequence mutable. If you wanted to keep the original sequence immutable, and just based on that define a new one, use sorted instead:

import std/algorithm

let my_seq = @[("a", "hello"), ("c", "world"), ("b", "to")]

let my_seq2 = sorted(my_seq)  # or sorted(my_seq, cmp)

echo(my_seq2)

Demo

All of them output:

@[("a", "hello"), ("b", "to"), ("c", "world")]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.