Hi All,
I'm trying to create a sequence of a subrange type as shown below:
type
Nucleotide = enum
T, A, G, C, U
DNANuc = range[T..C]
RNANuc = range[A..U]
echo high(DNANuc)
var dnaseq1: seq[DNANuc] = @[]
dnaseq1.add(A)
dnaseq1.add(T)
dnaseq1.add(T)
dnaseq1.add(G)
dnaseq1.add(C)
echo dnaseq1
# the following line gives a type mismatch error
var dnaseq2: seq[DNANuc] = @[A, T, T, G, C]
echo dnaseq2
As the example code indicates, creating an empty sequence and then filling with items from the enum via add() works, but initializing the sequence in one fell swoop doesn't work. From the error message obviously @[A, T, T, G] is being intepreted as seq[Nucleotide] instead of seq[DNANuc] but how do I force it to be interepreted as such?
That's because on the right and @[A, T, T, G, C] is a `seq[Nucleotide], the type is inferred from the type of the first item.
If you explicitly ask for a DNANuc on the first item it will work, for instance:
type
Nucleotide = enum
T, A, G, C, U
DNANuc = range[T..C]
RNANuc = range[A..U]
echo high(DNANuc)
var dnaseq1: seq[DNANuc] = @[]
dnaseq1.add(A)
dnaseq1.add(T)
dnaseq1.add(T)
dnaseq1.add(G)
dnaseq1.add(C)
echo dnaseq1
# the following line gives a type mismatch error
var dnaseq2: seq[DNANuc] = @[DNANuc A, T, T, G, C]
echo dnaseq2
var dnaseq2: seq[DNANuc] = @[DNANuc A, T, T, G, C]
Oh, that's nice! I didn't realize you only needed to constrain the first element. I usually say
var dnaseq2: seq[DNANuc] = @[A.DNANuc, T.DNANuc, T.DNANuc, G.DNANuc, C.DNANuc]