Code doesn't work - why?

Cliff via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 17 14:39:03 PDT 2014


On Wednesday, 17 September 2014 at 21:33:01 UTC, Robin wrote:
> Here is the fully working code for everyone experiencing 
> similar bugs or problems with pointers and value types. =)
>
> 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)) {
> 				writeln(currentState.toString() ~ " has no next for " ~ 
> to!string(c));
> 				break;
> 			} else {
> 				writeln(currentState.toString() ~ " has 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));
> }
>
> Regards,
> Rob

Out of curiosity, why did you decide to stick with structs
instead of simply using classes?  To avoid heap allocations?


More information about the Digitalmars-d-learn mailing list