Powerful match expressions

enum State{
    Normal,
    Comment,
    Upper,
    Lower
}

fn machine_cycle(state: State, c: char) -> (Option<char>, State){
    use self::State::*;
    match(state,c){
        (Normal, '#')=>(None, Comment),
        (Normal, '^')=>(None, Upper),
        (Normal, '_')=>(None, Lower),
        (Normal, other)=>(Some(other), Normal),
        (Comment, '#')=>(None, Normal),
        (Comment, _)=>(None, Comment),
        (Upper, '^')=>(None, Normal),
        (Upper, other)=>(Some(other.to_ascii_uppercase()),Upper),
        (Lower,'_')=>(None, Normal),
        (Lower,other)=>(Some(other.to_ascii_lowercase()),Lower),
    }
}

fn  main(){
    let mut state=State::Normal;
    let mut answer=String::new();
    let input="This _iS_ a New ^LinE^ #without this#";
    
    for cha in input.chars(){
        let (output,new_state)=machine_cycle(state,cha);
        if let Some(c)=output{
            answer.push(c);
        }
        state=new_state;
    }
    
    println!("{}",answer);
}

(Playground)

Output:

This is a New LINE 

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 1.56s
     Running `target/debug/playground`

2 Likes

Alternative formulation.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.