aboutsummaryrefslogtreecommitdiff
path: root/rust/nucleotide-count/src/lib.rs
blob: 98b0c38b1a79fe7685c7700d399da3eb0ab77b8d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use maplit::hashmap;
use std::collections::HashMap;

pub fn count(nucleotide: char, dna: &str) -> Result<usize, char> {
    nucleotide_counts(dna)?
        .remove(&nucleotide)
        .ok_or(nucleotide)
}

pub fn nucleotide_counts(dna: &str) -> Result<HashMap<char, usize>, char> {
    dna.chars().fold(
        Ok(hashmap![ 'A' => 0, 'C' => 0, 'G' => 0, 'T' => 0 ]),
        |acc, n| match n {
            'A' | 'C' | 'G' | 'T' => acc.map(|mut hmap| {
                hmap.entry(n).and_modify(|e| *e += 1).or_insert(0);
                hmap
            }),
            _ => Err(n),
        },
    )
}