chen
chen

Reputation: 157

Confusing behavior in Rust push method

I have a Formula which is defined like the following:

pub type Variable = char;

#[derive(Clone,Debug,PartialEq,Eq)]
pub enum Atom {
    Base(Variable),
    Not(Variable)
}

pub type Clause = Vec<Atom>;

pub type Formula = Vec<Clause>;

Next I have a method like so:

pub fn dpll(f:& mut Formula) -> bool {
    let mut formulaClone = f.clone();
    let v = 'a';
    let finalVect = formulaClone.push(vec![Atom::Base(v)]);
   
}

Now for some reason finalVect is assigned a type of (). I cannot figure out why? Shouldn't it be a type of &mut Formula? Because pushing to a vector doesn't change its type? Why does pushing to the vector modify its type in this case?

After hearing some suggestions: It seems like push method returns a () so how would I do the following then:

pub fn dpll(f:& mut Formula) -> bool {
    let mut formulaClone = f.clone();
    let v = 'a';
    let finalVect = formulaClone.push(vec![Atom::Base(v)]);
    let finalVect2 = formulaClone.push(vec![Atom::Not(v)]);
    return dpll(finalVect) || dpll(finalVect2);
}

In which case I want to recursively call dpll with the new parameters formulaClone + vec![Atom::Base(v)] and formulaClone + vec![Atom::Not(v)].

Upvotes: 0

Views: 93

Answers (1)

cafce25
cafce25

Reputation: 27461

You don't assign the return values of push to anything.

pub fn dpll(f: &mut Formula) -> bool {
    let mut formulaClone = f.clone();
    let v = 'a';
    formulaClone.push(vec![Atom::Base(v)]);
    let mut finalVect = formulaClone.clone();
    formulaClone.push(vec![Atom::Not(v)]);
    let mut finalVect2 = formulaClone.clone();
    return dpll(&mut finalVect) || dpll(&mut finalVect2);
}

if we go with your literal code.

Or a little more cleaned up:

pub fn dpll(mut f: Formula) -> bool {
    let v = 'a';
    f.push(vec![Atom::Base(v)]);
    let finalVect = f.clone();
    f.push(vec![Atom::Not(v)]);
    return dpll(finalVect) || dpll(f);
}

Upvotes: 2

Related Questions