DEV Community

Discussion on: Daily Challenge #212 - DNA to RNA

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Roost

fn dtoa(dna: &str) -> String {
    dna.chars().map(|c| match c {
        'G' | 'C' | 'A' => c,
        'T' => 'U',
        _ => panic!("you did this to yourself"),
    }).collect()
}
fn main() {
    for x in &["TTTT", "GCAT", "GACCGCCGCC", "💩"] {
        println!("{}=>{}", x, dtoa(x));
    }
}

"Rust"

use itertools::Itertools; // 0.9.0

#[derive(Debug)]
enum DToAError {
    Scat(usize, char),
}
use DToAError::*;

impl std::fmt::Display for DToAError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Scat(i, c) => write!(f, "Is this a joke? At index {}, what is `{}`?! No you can't \"have the processed values back\", get out!", i, c),
        }
    }
}

impl std::error::Error for DToAError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

fn dtoa(dna: &str) -> Result<String, DToAError> {
    dna.chars()
        .enumerate()
        .map(|(i, c)| {
            Ok(match c {
                'G' | 'C' | 'A' => c,
                'T' => 'U',
                _ => return Err(Scat(i, c)),
            })
        })
        .fold_results(String::with_capacity(dna.len()), |mut s, c| {
            s.push(c);
            s
        })
}
fn main() {
    for x in &["TTTT", "GCAT", "GACCGCCGCC", "💩"] {
        match dtoa(x) {
            Ok(res) => println!("{}=>{}", x, res),
            Err(err) => println!("{}=>OOPS: {}", x, err),
        }
    }
}

It works lol

When you don't listen at all

fn main() {
    for x in &["TTTT", "GCAT", "GACCGCCGCC", "💩"] {
        println!("{}=>{}", x, x.replace('T', "U"))
    }
}