Hamming
Count the positions at which two DNA strands differ; strands of different lengths are an error.
Adapted from Exercism’s problem specification (MIT). Listed under Strings & Text.
// FILE: hamming.nomi
//# The Hamming distance between two DNA strands.
/// The number of positions at which two DNA strands differ. Strands of
/// different lengths have no Hamming distance.
pub fn distance(strand1: String, strand2: String) -> Result<Int, String>
if String.length(strand1) != String.length(strand2) then
return Err("strands must be of equal length")
end
Iter.zip(strand1, strand2)
|> Iter.count_by(fn (a, b) -> a != b)
|> Ok()
end
// FILE: hamming_test.nomi
import hamming.distance
test "hamming distance"
[
("empty strands", "", "", Ok(0)),
("single letter identical strands", "A", "A", Ok(0)),
("single letter different strands", "G", "T", Ok(1)),
("long identical strands", "GGACTGAAATCTG", "GGACTGAAATCTG", Ok(0)),
("long different strands", "GGACGGATTCTG", "AGGACGGATTCT", Ok(9)),
("disallow first strand longer", "AATG", "AAA", Err("strands must be of equal length")),
("disallow second strand longer", "ATA", "AGTG", Err("strands must be of equal length")),
("disallow empty first strand", "", "G", Err("strands must be of equal length")),
("disallow empty second strand", "G", "", Err("strands must be of equal length")),
]
|> subtests (description, strand1, strand2, expected), description
assert distance(strand1, strand2) == expected
end
endok hamming distance (9 cases)
test result: ok. 9 passed, 0 failed
How it’s written
Section titled “How it’s written”- The result is
Result<Int, String>with the canonical message as the error, rather than a one-variant error enum. There is one failure and its message is the useful part; an enum with a single variant would be a name for the same string. - The length check is an early
return Err(...), and the count is azippiped intoIter.count_by, ending in|> Ok(). Strings iterate by grapheme, soIter.zip(strand1, strand2)pairs the letters directly. - Every reimplemented error case uses its newest version, all with the message “strands must be of equal length”. That leaves nine cases: five distances and four errors.