I am learning enum and I wonder if it is possible (does it make sense is a different story) to sort value in enum?
import algorithm
type
Candidates = enum
CanB = 2
CanA = 3
echo sorted(Candidates). # Error: type mismatch: got <type Candidates>
I want to see:
does it make sense
no. sorted works on seqs or arrays, not types, and sorting an enum has no purpose
it is possible
of course! 😄
import algorithm,sugar
type
Candidates = enum
CanB = 2
CanA = 3
proc cmpById(e,f: enum):int = cmp($e,$f)
echo sorted(collect(newSeq,for c in Candidates:c),cmpById)
echo sorted(collect(newSeq,for c in Candidates:c))
import algorithm
type
Foo = enum
barC = 1
barB = 2
barA = 3
barD = 4
var x = [Foo.barB, Foo.barA, Foo.barD, Foo.barC]
#Sort by value
echo sorted(x)
#Sort by identifier
echo sortedByIt(x, $it)
Thank you! Wow, I need to learn 'collect' and 'sequences' to understand what is going on with the proc 'cmpById' :-)
However, adding a new member at the end: 'CanC = 5' results with Error: type mismatch: got <Candidates> again.
import algorithm,sugar
type
Candidates = enum
CanB = 2
CanA = 3
CanC = 5 # <== new member
proc cmpById(e,f: enum):int = cmp($e,$f)
echo sorted(collect(newSeq,for c in Candidates:c),cmpById)
echo sorted(collect(newSeq,for c in Candidates:c))
error: .choosenim/toolchains/nim-1.4.6/lib/system/iterators_1.nim(85, 12) Error: type mismatch: got <Candidates>
but expected one of:
expression: inc(res)
In 1.5.1 (choosenim devel) there's a module enumutils which allows iteration over enum with non-contiguous members.
import std/[algorithm,enumutils,sugar]
type
Candidates = enum
CanB = 2
CanA = 3
CanC = 5 # <== new member
proc cmpById(e,f: enum):int = cmp($e,$f)
echo sorted(collect(newSeq,for c in Candidates:c),cmpById)
echo sorted(collect(newSeq,for c in Candidates:c))
... crap
I <3 Nim to the max but when this sorta thing happens I do get a bit downhearted.
testing max integer in enum:
type
E = enum
Ea = 9223372036854775806. # works fine
# Eb = high(int) # fatal.nim(49) sysFatal Error: unhandled exception: over- or underflow [OverflowDefect]
I love this:
type
Candidate = enum
Candidate_a = "aa"
Candidate_b = "first last_name"
for i in Candidate:
echo i
sorting works with seq:
import algorithm
type
Candidate = enum
Candidate_a = "zzz_kast"
Candidate_b = "aaa_first last_name"
proc enumToStrings(en: typedesc): seq[string] =
for x in en:
result.add $x
var s = enumToStrings(Candidate)
s.sort()
echo s
s.reverse()
echo s