Skip to content

Protein Translation

Translate an RNA strand, three nucleotides at a time, into the amino acids of its protein, stopping at the first STOP codon.

Adapted from Exercism’s problem specification (MIT). Listed under Encoding & Ciphers.

// FILE: protein_translation.nomi
//# Translates an RNA strand, three nucleotides at a time, into the amino
//# acids of its protein.

/// The amino acids the exercise's codons stand for.
pub enum AminoAcid
    Methionine
    Phenylalanine
    Leucine
    Serine
    Tyrosine
    Cysteine
    Tryptophan
end

/// Why a strand does not translate.
pub enum Error
    /// A codon before the first STOP that stands for nothing, given as it
    /// appears in the strand: three letters, or fewer at the strand's end.
    InvalidCodon String
end

/// The amino acids `strand`'s codons stand for, up to its first STOP codon.
/// Whatever follows a STOP is not read.
pub fn proteins(strand: String) -> Result<List<AminoAcid>, Error>
    strand
    |> Iter.chunks(3)
    |> Iter.map(String.join)
    |> Iter.map(translate)
    |> Iter.take_while(&(&1 != Ok(None)))
    |> Result.collect()?
    |> Maybe.values()
    |> Iter.to_list()
    |> Ok()
end

/// The amino acid `codon` stands for, `None` for a STOP codon.
fn translate(codon: String) -> Result<Maybe<AminoAcid>, Error>
    case codon
        "AUG"                            -> Ok(Some(.Methionine))
        "UUU" or "UUC"                   -> Ok(Some(.Phenylalanine))
        "UUA" or "UUG"                   -> Ok(Some(.Leucine))
        "UCU" or "UCC" or "UCA" or "UCG" -> Ok(Some(.Serine))
        "UAU" or "UAC"                   -> Ok(Some(.Tyrosine))
        "UGU" or "UGC"                   -> Ok(Some(.Cysteine))
        "UGG"                            -> Ok(Some(.Tryptophan))
        "UAA" or "UAG" or "UGA"          -> Ok(None)
        _                                -> Err(.InvalidCodon(codon))
    end
end

// FILE: protein_translation_test.nomi
import
    protein_translation
    protein_translation.{AminoAcid, Error}
end

test "proteins"
    [
        ("Empty RNA sequence results in no proteins", "",    []),
        ("Methionine RNA sequence",                   "AUG", [AminoAcid.Methionine]),
        ("Phenylalanine RNA sequence 1",              "UUU", [.Phenylalanine]),
        ("Phenylalanine RNA sequence 2",              "UUC", [.Phenylalanine]),
        ("Leucine RNA sequence 1",                    "UUA", [.Leucine]),
        ("Leucine RNA sequence 2",                    "UUG", [.Leucine]),
        ("Serine RNA sequence 1",                     "UCU", [.Serine]),
        ("Serine RNA sequence 2",                     "UCC", [.Serine]),
        ("Serine RNA sequence 3",                     "UCA", [.Serine]),
        ("Serine RNA sequence 4",                     "UCG", [.Serine]),
        ("Tyrosine RNA sequence 1",                   "UAU", [.Tyrosine]),
        ("Tyrosine RNA sequence 2",                   "UAC", [.Tyrosine]),
        ("Cysteine RNA sequence 1",                   "UGU", [.Cysteine]),
        ("Cysteine RNA sequence 2",                   "UGC", [.Cysteine]),
        ("Tryptophan RNA sequence",                   "UGG", [.Tryptophan]),
        ("STOP codon RNA sequence 1",                 "UAA", []),
        ("STOP codon RNA sequence 2",                 "UAG", []),
        ("STOP codon RNA sequence 3",                 "UGA", []),
        (
            "Sequence of two protein codons translates into proteins",
            "UUUUUU",
            [.Phenylalanine, .Phenylalanine],
        ),
        (
            "Sequence of two different protein codons translates into proteins",
            "UUAUUG",
            [.Leucine, .Leucine],
        ),
        (
            "Translate RNA strand into correct protein list",
            "AUGUUUUGG",
            [.Methionine, .Phenylalanine, .Tryptophan],
        ),
        ("Translation stops if STOP codon at beginning of sequence",     "UAGUGG", []),
        ("Translation stops if STOP codon at end of two-codon sequence", "UGGUAG", [.Tryptophan]),
        (
            "Translation stops if STOP codon at end of three-codon sequence",
            "AUGUUUUAA",
            [.Methionine, .Phenylalanine],
        ),
        (
            "Translation stops if STOP codon in middle of three-codon sequence",
            "UGGUAGUGG",
            [.Tryptophan],
        ),
        (
            "Translation stops if STOP codon in middle of six-codon sequence",
            "UGGUGUUAUUAAUGGUUU",
            [.Tryptophan, .Cysteine, .Tyrosine],
        ),
        (
            "Sequence of two non-STOP codons does not translate to a STOP codon",
            "AUGAUG",
            [.Methionine, .Methionine],
        ),
        (
            "Incomplete RNA sequence can translate if valid until a STOP codon",
            "UUCUUCUAAUGGU",
            [.Phenylalanine, .Phenylalanine],
        ),
    ]
    |> subtests (description, strand, expected), description
        assert protein_translation.proteins(strand) == Ok(expected)
    end
end

test "invalid codons"
    [
        (
            "Unknown amino acids, not part of a codon, can't translate",
            "XYZ",
            Error.InvalidCodon("XYZ"),
        ),
        ("Incomplete RNA sequence can't translate", "AUGU", .InvalidCodon("U")),
    ]
    |> subtests (description, strand, expected), description
        assert protein_translation.proteins(strand) == Err(expected)
    end
end
  • Amino acids are an AminoAcid enum, not the canonical strings.
  • The error is Error.InvalidCodon(String), carrying the codon that did not translate: "XYZ", or the short tail "U" of "AUGU". The canonical data gives only the message “Invalid codon”.
  • proteins is one pipeline: Iter.chunks(3) cuts the codons, translate reads each as Result<Maybe<AminoAcid>, Error> with Ok(None) for STOP, Iter.take_while stops at the first STOP, Result.collect()? passes the first error up, and Maybe.values unwraps the amino acids. Because take_while is lazy, nothing after a STOP is read, which is why "UUCUUCUAAUGGU" translates despite its short tail.
  • STOP is None rather than a variant of a private Codon enum. A Codon enum names it better, but its Stop would have to be filtered out again after take_while, the same as None is.
  • Iter.map(String.join) passes the function itself: where a function of one parameter is expected, String.join takes its default separator.
  • “Non-existing codon can’t translate” ("AAA") is left out: “Unknown amino acids, not part of a codon, can’t translate” reimplements it.
  • The success table has no type annotation. Its first row’s expected list is [], and its second row writes AminoAcid.Methionine qualified, so the bare variants in later rows take AminoAcid from it.