Code doesn't work - why?

Robin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Sep 16 21:08:45 PDT 2014


Hello,

I came back to D after a longer break and just wanted to set up a 
small project to further get in contact with this language.

However, it seems that the codes which simply shall simulate a 
deterministic finit automaton do not work correctly.

CODE ---

struct DeterministicState {
public:
	this(string name, bool isFinal, DeterministicState[char] 
transits...) {
		this.name = name;
		this.finalState = isFinal;
		this.addTransits(transits);
	}

	this(string name, bool isFinal) {
		this.name = name;
		this.finalState = isFinal;
	}

	this(bool isFinal, DeterministicState[char] transits...) {
		this("", isFinal, transits);
	}

	this(DeterministicState[char] transits...) {
		this("", false, transits);
	}

	void addTransits(DeterministicState[char] newTransits) {
		foreach (immutable key; newTransits.keys) {
			transits[key] = newTransits[key];
		}
	}

	string getName() const {
		return name;
	}

	bool isFinalState() const {
		return finalState;
	}

	bool hasNext(char input) const {
		return (input in transits) ? true : false;
	}

	DeterministicState getNext(char input) {
		return transits[input];
	}

	string toString() const {
		return name;
	}

private:
	string name;
	DeterministicState[char] transits;
	bool finalState;
}

struct DeterministicFiniteAutomaton {
public:
	DeterministicState[] input(char[] input) {
		DeterministicState[] trace = [ start ];
		auto currentState = trace[0];
		foreach (immutable c; input) {
			if (currentState.hasNext(c) == false) {
				writeln(currentState.toString() ~ " has next for " ~ 
to!string(c));
				break;
			} else {
				writeln(currentState.toString() ~ " has NO next for " ~ 
to!string(c));
			}
			currentState = currentState.getNext(c);
			trace ~= currentState;
		}
		return trace;
	}

	this(DeterministicState start) {
		this.start = start;
	}

private:
	DeterministicState start;
}

void main()
{
	auto s0 = DeterministicState("s0", false);
	auto s1 = DeterministicState("s1", false);
	auto s2 = DeterministicState("s2", true);
	s0.addTransits(['0' : s1, '1' : s2]);
	s1.addTransits(['0' : s0, '1' : s2]);
	s2.addTransits(['0' : s2, '1' : s2]);
	auto dfa = DeterministicFiniteAutomaton(s0);
	auto trace = dfa.input("0001".dup);
	foreach (t; trace) {
		writeln(t.toString());
	}
	writeln("Trace Length = " ~ to!string(trace.length));
}

---

The output is the following:

s0 has NO next for 0
s1 has next for 0
s0
s1
Trace Length = 2

Which states that the trace for input "0001" has just a length of 
2 instead of 4. And I do not really understand why s1 has no next 
item while it was defined in main.

I hope someone can clear things up for me. I really don't get why 
this isn't working as intended.

Regards,
Rob


More information about the Digitalmars-d-learn mailing list