67192

Error in Defining an associative array in D

Question:

So I would like to implement a hash lookup for translating codons to amino acids in D. When i write

int[string] codon_table = [ "ATG": 'M', "TTT": 'F', "TTC": 'F', "TTA": 'L', "TTG": 'L', "CTT": 'L', "CTC": 'L', "CTA": 'L', "CTG": 'L', "ATT": 'I', "ATC": 'I', "ATA": 'I', "GTT": 'V', "GTC": 'V', "GTA": 'V', "GTG": 'V', "TCT": 'S', "TCC": 'S', "TCA": 'S', "TCG": 'S', "CCT": 'P', "CCC": 'P', "CCA": 'P', "CCG": 'P', "ACT": 'T', "ACC": 'T', "ACG": 'T', "GCT": 'A', "GCC": 'A', "GCA": 'A', "GCG": 'A', "TAT": 'Y', "TAC": 'Y', "TAA": '*', "TAG": '*', "CAT": 'H', "CAC": 'H', "CAA": 'Q', "CAG": 'Q', "AAT": 'N', "AAC": 'N', "AAA": 'K', "AAG": 'K', "GAT": 'D', "GAC": 'D', "GAA": 'E', "GAG": 'E', "TGT": 'C', "TGC": 'C', "TGA": '*', "TGG": 'W', "CGT": 'R', "CGC": 'R', "CGA": 'R', "CGG": 'R', "AGT": 'S', "AGC": 'S', "AGA": 'R', "AGG": 'R', "GGT": 'G', "GGC": 'G', "GGA": 'G', "GGG": 'G' ];

The code does not compile and I get

Error: no-constant expression

I think this is slightly odd because I though it would trivial to write an associate array as a constant and use it as a lookup table. When I append enum for example;

enum int[string] codon_table = [...]

it seems to work.

What are the tradeoffs of using enum vs static int[string] when defining this sort of associative array? What am I doing wrong?

Answer1:

Try this:

immutable int[string] codon_table; static this() { codon_table = [ "ATG": 'M', // ... "GGA": 'G', "GGG": 'G' ]; }

I made the table immutable since it's unlikely that you're going to need to change a lookup table.

That said, it's a bit weird that your initializer doesn't work. You might want to post this on the D forums.

Recommend