How to sort a sequence in Nim?
Asked Answered
S

2

10

I have a sequence generated by list comprehension as follows:

var a_bigram_list = lc[a[i..i+2] | (i <- 0..<len(a)), string]

Now, I would like to sort it but sort(a_bigram_list) will result in the following compilation error

Error: type mismatch: got (seq[string])
but expected one of: 
proc sort[A, B](t: OrderedTableRef[A, B]; cmp: proc (x, y: (A, B)): int)
proc sort[A, B](t: var OrderedTable[A, B]; cmp: proc (x, y: (A, B)): int)
proc sort[A](t: CountTableRef[A])
proc sort[A](t: var CountTable[A])
proc sort[T](a: var openArray[T]; cmp: proc (x, y: T): int; order = SortOrder.Ascending)

Is there any way of sorting a sequence? Or do I need to convert it to array? If so, can is there a way to obtain an array from lc?

Spontaneity answered 1/3, 2017 at 11:11 Comment(0)
B
11

sort works with sequences (openArray is a generic parameter type that accepts both arrays and seqs), but it expects a comparison proc as a second parameter.

You can provide it a default cmp from system module:

sort(a_bigram_list, system.cmp)
Buckinghamshire answered 1/3, 2017 at 11:36 Comment(2)
How an own, local implementation of the compare method would look like?Muricate
A custom sort example: nim-lang.org/docs/algorithm.html#basic-usageGravedigger
L
3

As of October 2018, your intended code sort(a_bigram_list) will now work just fine, since sort[T](...) now uses system.cmp[T] as the implied sort function if you only provide one argument.

Landrum answered 28/2, 2023 at 1:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.