These are chat archives for rust-lang/rust

25th
Mar 2015
Daniel Ferreira Monteiro Alves
@danfma
Mar 25 2015 04:05
hey guys!
Matthew Carroll
@msc654
Mar 25 2015 04:05
hey
Daniel Ferreira Monteiro Alves
@danfma
Mar 25 2015 04:06
I am playing with rust for a while, but when using some object oriented programming I get lost
while we don’t have oo really but that’s another story! :P
how could I rewrite this code in some cool rust code
// Playground - noun: a place where people can play

class DFA {
    var symbols: [Character] = []
    var states: [String] = []
    var transitions: [String: [Character: String]] = [String: [Character: String]]()
    var start: String = "0"
    var acceptedStates: [String] = []

    func accept(word: String) -> Bool {
        var currentState = self.start

        for char in word {
            let movements = self.transitions[currentState]!

            currentState = movements[char]!
        }

        return contains(acceptedStates, currentState)
    }
}


let dfa = DFA()

dfa.symbols = ["0", "1"]
dfa.states = ["A", "B"]
dfa.start = dfa.states.first!
dfa.acceptedStates = ["B"]
dfa.transitions = [
    "A": [
        "0": "A",
        "1": "B"
    ],
    "B": [
        "0": "A",
        "1": "B"
    ]
]

dfa.accept("0011")
dfa.accept("01010")
I am just playing a little with it so it’s nothing really serious!
hey too, @msc654 !
Peter Atashian
@retep998
Mar 25 2015 04:08
You can use the Default trait to provide default values for things
Daniel Ferreira Monteiro Alves
@danfma
Mar 25 2015 04:09
hummm ok… but the real problem was with arrays
the compiler hits on my head abou the lifetime usage of some variables
```rust
ops
use std::collections::HashMap;

type TransitionTable = HashMap<String, HashMap<char, String>>;


struct DFA {
    symbols: [char; 2],
    states: [String; 2],
    transitions: TransitionTable,
    start: String,
    acceptedStates: [String; 1]
}


fn main() {
    let dfa = DFA {
        symbols: ['0', '1'],
        states: ["A", "B"],
        transitions: TransitionTable::new(),
        start: "A",
        acceptedStates: ["B"]
    };
}
I just started with this, but it is far away from the first and with a lot of errors!
I don’t want to specify the sizes of arrays on the struct too… maybe I have to change arrays for vectors, I don’t know!
:)
thanks @retep998 , I will check that too
Daniel Ferreira Monteiro Alves
@danfma
Mar 25 2015 05:27
I could only get this far from an equivalent code… does anybody have any hints?
use std::collections::HashMap;


struct Transition(i32, char, i32);


struct DFA {
    symbols: Vec<char>,
    states: Vec<String>,
    transitions: Vec<Transition>,
    start: i32,
    final_states: Vec<i32>
}

impl DFA {
    pub fn accept(&self, word: &str) -> bool {
        let mut current_state = self.start;

        for c in word.chars() {            
            for transition in self.transitions.iter() {
                let Transition(start, symbol, end) = *transition;

                if start == current_state && symbol == c {
                    current_state = end;
                    break;
                }
            }
        }

        return self.is_final_state(current_state);
    }

    fn is_final_state(&self, state: i32) -> bool {
        for final_state in self.final_states.iter() {
            if *final_state == state {
                return true;
            }
        }

        return false;
    }
}


fn main() {
    let symbols = vec!['0', '1'];
    let states = vec![String::from_str("A"), String::from_str("B")];
    let final_states = vec![1];

    let transitions = vec![
        Transition(0, '0', 0),
        Transition(0, '1', 1),
        Transition(1, '0', 0),
        Transition(1, '1', 1)
    ];

    let dfa = DFA {
        symbols: symbols,
        states: states,
        transitions: transitions,
        start: 0,
        final_states: final_states
    };

    let word = "0011";
    let accepted = dfa.accept(word);

    println!(
        "This DFA accepts the word '{}'? {}",
        word,
        accepted
    );
}
Peter Atashian
@retep998
Mar 25 2015 05:30
I'd recommend HashMap<(i32, char), i32> for transitions
You can convert "A" to a String using "A".to_owned()
Daniel Ferreira Monteiro Alves
@danfma
Mar 25 2015 13:38
hummm ok...
the previous code used strings as keys and a multi key dictionary
I will modify the code but anyway, while I love the rust, I have to agree that the ammount of code is bigger than the previous in Swift or other in C#
I have another point to discuss… If I create a low level library, in rust, to be used by external codes in C#, for example… How will be the behaviour to handle memory objects that goes out of the scope of the library?
Vladislav Nezhutin
@exe-dealer
Mar 25 2015 14:43

Is there way to use metavariable as part of identifier?

macro_rules! fun {
    ($x:ident) => {
        fn fun_$x() {}
    }
}

fun!(one);

produces

<anon>:3:16: 3:18 error: expected one of `(` or `<`, found `one`
<anon>:3         fn fun_$x() {}
                        ^~
playpen: application terminated with error code 101
Pierre Krieger
@tomaka
Mar 25 2015 15:15
@exe-dealer No, not possible
that's often asked
Daniel Ferreira Monteiro Alves
@danfma
Mar 25 2015 15:41

hey again! ;)
When I wrote the code bellow I have the error main.rs:21:17: 21:35 error: typestd::collections::hash::map::HashMap<TransitionKey<'_>, &collections::string::String>does not implement any method in scope namednewmain.rs:21 transitions: TransitionMap::new(),:

type State<'a> = &'a String;
struct TransitionKey<'a>(State<'a>, char);
type TransitionMap<'a, 'b> = HashMap<TransitionKey<'a>, State<'b>>;

struct DFA<'s> {
    symbols: Vec<char>,
    states: Vec<State<'s>>,
    transitions: TransitionMap<'s, 's>,
    start: Option<State<'s>>,
    final_states: Vec<State<'s>>
}

impl <'s> DFA<'s> {
    pub fn new() -> DFA<'s> {
        DFA {
            symbols: vec![],
            states: vec![],
            transitions: TransitionMap::new(),
            start: None,
            final_states: vec![]
        }
    }

But how can I create a HashMap inside a struct so that HashMap instance is owned by the same lifetime of the struct instance?