Creating a deterministic finite automata (DFA) - Mercury - mercury

I would like to have a deterministic finite automata (DFA) simulated in Mercury.
But I’m s(t)uck at several places.
Formally, a DFA is described with the following characteristics:
a setOfStates S,
an inputAlphabet E <-- summation symbol,
a transitionFunction : S × E --> S,
a startState s € S,
a setOfAcceptableFinalStates F =C S.
A DFA will always starts in the start state.
Then the DFA will read all the characters on the input, one by one.
Based on the current input character and the current state, there will be made
to a new state.
These transitions are defined in the transitions function.
when the DFA is in one of his acceptable final states, after reading the last character, then will the DFA accept the input, If not, then the input will be is rejected.
The figure shows a DFA the accepting strings where the amount of zeros, is a plurality of three. Condition 1 is the initial state, and also the only acceptable state. for each input character is the corresponding arc followed to the next state.
Link to Figure
What must be done
A type “mystate” which represents a state. Each state has a number which is used for
identification.
A type “transition” that represents a possible transition between states.
Each transition has a source_state, an input_character, and a final_state.
A type “statemachine” that represents the entire DFA. In the solution, the DFA must have the following properties:
The set of all states,
the input alphabet,
a transition function, represented as a set of possible transitions,
a set of accepting final states,
a current state of the DFA
A predicate “init_machine (state machine :: out)” which unifies his arguments with the
DFA, as shown as in the Figure.
The current state for the DFA is set to his initial state, namely, 1. The input alphabet of the DFA is composed of the characters '0'and '1'.
A user can enter a text, which will be controlled by the DFA. the program will
continues until the user types Ctrl-D and simulates an EOF. If the user use
characters that are not allowed into the input alphabet of the DFA, then there will be an error message end the program will close. (pred require)
Example
Enter a sentence: 0110
String is not ok!
Enter a sentence: 011101
String is not ok!
Enter a sentence: 110100
String is ok!
Enter a sentence: 000110010
String is ok!
Enter a sentence: 011102
Uncaught exception Mercury:
Software Error: Character does not belong to the input alphabet!
the thing wat I have.
:- module dfa.
:- interface.
:- import_module io.
:- pred main(io.state::di, io.state::uo) is det.
:- implementation.
:- import_module int,string,list,bool.
1
:- type mystate ---> state(int).
2
:- type transition
---> trans(
source_state::mystate,
input_character::bool,
final_state::mystate
).
3 (error, finale_state and current_state and input_character)
:- type statemachine
---> dfa(
list(mystate),
list(input_character),
list(transition),
list(final_state),
current_state(mystate)
).
4 missing a lot
:- pred init_machine(statemachine :: out) is det.
%init_machine(statemachine(L_Mystate,0,L_transition,L_final_state,1)) :- <-probably fault
5 not perfect
main(!IO) :-
io.write_string("\nEnter a sentence: ", !IO),
io.read_line_as_string(Input, !IO),
(
Invoer = ok(StringVar),
S1 = string.strip(StringVar),
(if S1 = "mustbeabool" then
io.write_string("Sentenceis Ok! ", !IO)
else
io.write_string("Sentence is not Ok!.", !IO)),
main(!IO)
;
Invoer = eof
;
Invoer = error(ErrorCode),
io.format("%s\n", [s(io.error_message(ErrorCode))], !IO)
).
Hope you can help me
kind regards

When you write a type such as mystate:
:- type transition ---> trans(source_state::mystate, input_character::bool, final_state::mystate).
Don't write it out all on one line, it is difficult to read.
:- type transition
---> trans(
source_state :: mystate,
input_character :: bool,
final_state :: mystate
).
Now it is much easier to read. We can also see that the types and field names are arround the wrong way. Try:
:- type transition
---> trans(
mystate :: source_state,
bool :: input_character,
mystate :: final_state
).

Related

How to set mutually exclusive probabilities in Problog?

A person X can either be inpatient or outpatient.
Given the fact location(X,outpatient) how can Problog infer that the probability of location(X,inpatient) is 0?
For example I want a side effect of:
person(1).
location(1,inpatient).
dependent(1,opioids).
receive(1,clonidine).
query(detoxification(1,opioids,success)).
to be an inference that location(1,outpatient) has zero probability.
If I write location(X,outpatient);location(X,inpatient)., all queries return both with a probability of 1.
If I write P::location(X,outpatient);(1-P)::location(X,inpatient). that gives an error because I haven't specified a value for P. If I specify a value for P, that value is never updated (as expected because Prolog treats variables as algebraic variables and I haven't told Problog to update P.
If I write location(X,outpatient) :- \+ location(X,inpatient). I create a negative cycle, which I have to if I am to specify the inverse goal.
One solution:
P::property(X,location,inpatient);(1-P)::property(X,location, outpatient) :-
inpatient(X),
P is 1.
P::property(X,location,outpatient);(1-P)::property(X,location, inpatient) :-
outpatient(X),
P is 1.
P::inpatient(X);(1-P)::outpatient(X) :-
property(X,location,inpatient),
P is 1.
P::outpatient(X);(1-P)::inpatient(X) :-
property(X,location,outpatient),
P is 1.
This binds inpatient/1 to property/3 for the property of location with value inpatient.

Syntactic analysis - prolog

I have a Definite Clause Grammar: S → a S b | ɛ .
This was also written as the following rules: s --> [a], s, [b]. and s --> [].
This was translated to Prolog as follows:
s --> [a], s, [b]. became s([a|S2],R) :- s(S2,[b|R]).
s --> []. became s(S,S).
Can somebody tell me what the value of S2 is here? Where does S2 come from?
It looks like this is a program to determine if a list is of the form an . X . bn, where an means n iterations of a, and similarly, bn means n iterations of b.
s --> [a], s, [b]. becomes s([a|S2],R) :- s(S2,[b|R]).
s --> []. becomes s(S,S).
Here S2 is the middle of the list, a free variable that a part of the list can be bound to.
Naming it S2 is completely arbitrary. It could also have been called S.
The only thing it should not be called is R, as that is already used for another variable in that statement.
What matters is what is bound to it - the tail of the list. If this predicate is tried on any list starting with a, then S2 will be bound to the tail.
A few examples to illustrate it:
If the input was [a,a,b,b], the value of S2 would be [a,b,b].
If the input was [a], the value of S2 would be the empty list [].
If the input was [a,x,y,z], the value of S2 would be [x,y,z].
If the input was [b,c,d,e], then it would not match, and S2 would not be bound to anything; instead, the predicate would fail.
Note that [a,x,y,z] actually matches the predicate, despite the fact that it is not of the form an . X . bn.
The rule only looks at the first item, a, and notices that that matches. So it derives s([x,y,z],[b|R]). Then it will try to continue verifying the input. Only in a later derivation step will it notice that [x,y,z] does not start with a.
Let's go through this step by step.
First we have:
s([a,x,y,z],R) :- s([x,y,z],[b|R]).
This works, and Prolog binds S2 to [x,y,z].
Then it gets s([x,y,z],R), but it cannot match that to s([a|S2]), because it does not start with a, and so this time the rule fails.
Now it tries the next rule: s(S,S). It fills in: s([x,y,z],[x,y,z]).
With this, it goes back to its earlier call, and tries to match s([x,y,z],[x,y,z]) to its earlier rule s([x,y,z],[b|R]).
It cannot match the [x,y,z] on the rigthand side to [b|R] because it does not start with b. And this is where the rule fails - Prolog has decided that the string is not of the form an.bn.
To see how R is used, let's look at a trace of a list that does match.
s([a,a,b,b],R):-s([a,b,b],[b|R]). /* We haven't got a value for R yet. */
s([a,b,b],R):-s([b,b],[b|R]). /* We haven't got a value for R yet. */
s([b,b],[b,b]). /* Stop condition for the recursion. */
At this point, the righthand side is instantiated to [b,b].
Prolog had s([a,b,b],[b|R]) in the previous step, and it can now make this succeed by setting R=[b].
It then further unwinds the recursion, filling in values for the righthand side of the rule and applying these values to the lefthand side. Eventually it returns to where it started, and has the value s([a,a,b,b],[a,a,b,b]).

Theory of Computation. Turing Machine

Click here for the answer. Turing Machine
The question is to construct a Turing Machine which accepts the regular expression,
L = {a^n b^n | n>= 1}.
I am not sure if my answer is correct or wrong. Thank you in advance for your reply.
You cannot "accept the regular expression", only the language it describes. And what you provide is not a regular expression, but a set description. In fact, the language is not regular and therefore cannot be described by standard regular expressions.
The machine from your answer accepts the language described by the regular expression a^+ b^+.
A TM could mark the first a (e.g. by converting it to A) then delete the first b. And for each n one loop. If you and up with a string only of A, then accept.
As stated before, language L = {a^nb^n; n >= 1} cannot be described by regular expressions, it doesn't belong into the category of regular grammars. This language in particular is an example of context-free grammar, and thus it can be described by context-free grammar and recognized by pushdown automaton (an automaton with LIFO memory, a stack).
Grammar for this language would look something like this:
G = (V, S, R, P)
Where:
V is finite set of non-terminal characters, V = { S }
S is finite set of terminal characters, S = { a, b }
R is relation that describes "rewrites" from non-terminal characters to non-terminals and terminals, in this case R = { S -> aSb, S -> ab }
P is starting non-terminal character, P = S
A pushdown automata recognizing this language would be more complex, as it is a 7-tuple M = (Q, S, G, D, q0, Z, F)
Q is set of states
S is input alphabet
G is stack alphabet
D is the transition relation
q0 is start state
Z is initial stack symbol
F is set of accepting states
For our case, it would be:
Q = { q0, q1, qF }
S = { a, b }
G = { z0, X }
D will take a form of relation (current state, input character, top of stack) -> (output state, top of stack) (meaning you can move to a different state and rewrite top of stack (erase it, rewrite it or let it be)
(q0, a, z0) -> (q0, Xz0) - reading the first a
(q0, a, X) -> (q0, XX) - reading consecutive a's
(q0, b, X) -> (q1, e) - reading first b
(q1, b, X) -> (q1, e) - reading consecutive b's
(q1, e, z0) -> (qF, e) - reading last b
where e is empty word (sometimes called epsilon)
q0 = q0
Z = z0
F = { qF }
The language L = {a^n b^n | n≥1} represents a kind of language where we use only 2 character, i.e., a, b. In the beginning language has some number of a’s followed by equal number of b’s . Any such string which falls in this category will be accepted by this language. The beginning and end of string is marked by $ sign.
Step-1:
Replace a by X and move right, Go to state Q1.
Step-2:
Replace a by a and move right, Remain on same state
Replace Y by Y and move right, Remain on same state
Replace b by Y and move right, go to state Q2.
Step-3:
Replace b by b and move left, Remain on same state
Replace a by a and move left, Remain on same state
Replace Y by Y and move left, Remain on same state
Replace X by X and move right, go to state Q0.
Step-5:
If symbol is Y replace it by Y and move right and Go to state Q4
Else go to step 1
Step-6:
Replace Y by Y and move right, Remain on same state
If symbol is $ replace it by $ and move left, STRING IS ACCEPTED, GO TO FINAL STATE Q4

How to shortern a predicate that prints depending on a condition

So I have something like this:
main :-
% Check whether B,C,D is equal to A
... ,
% Relevant code:
(
(B==A -> write('B is the same as A.'));
(C==A -> write('C is the same as A.'));
(D==A -> write('D is the same as A.'));
).
Is there any way that this could be shortened but still print the relevant letter? There could be 100's of letters to test so this current method is not very nice.
Just a quick note in case you weren't aware of this difference: When you call A == B, you're resting whether the value bound to the variable A is equivalent to the value bound to variable B. But when you use write/1 to output
'B is the same as A.', you are just outputting the atomic literal represented by that string of letters. There is no relationship between the character 'A' as part of an atom and the value bound to a variable which is represented by A (no ') in your source code.
So I'm not 100% clear on your intended result, but here are two different solutions that demonstrate the use of the format family of predicates for outputting values and literals:
If you just want to compare the values of two variables, you can use a predicate to perform the comparison and printout the desired result, which can then be used on all members of a list (forall/2 is appropriate here because we are only concerned with output):
report_on_equality(A, B) :-
A == B,
format('~w is the same as ~w.~n', [A, B]).
report_on_equality(A, B) :-
A \== B,
format('~w is not the same as ~w.~n', [A, B]).
example_1 :-
Vals = [1,4,6,1,7],
forall( member(V, Vals),
report_on_equality(V, 1)
).
But there is no reason to output the value of the variables twice in this case, since if they are equivalent, they will of course be the same value. So maybe you actually want to print out uppercase characters that have been previously associated with values. This, of course, requires that you have first made some paring between uppercase characters and some other values. I have chosen to use a simple list of pairs for this purpose:
report_on_labeled_equality(LabelA-ValA, LabelB-ValB) :-
ValA == ValB,
format('~w is the same as ~w.~n', [LabelA, LabelB]).
report_on_labeled_equality(LabelA-ValA, LabelB-ValB) :-
ValA \== ValB,
format('~w is not the same as ~w.~n', [LabelA, LabelB]).
example_2 :-
Vals = ['B'-1, 'C'-3, 'D'-1, 'E'-4],
forall( member(V, Vals),
report_on_labeled_equality(V, 'A'-1)
).

Prompt does not come back

I try to do some exercise - to represent numbers in "s representation" which means '0' is zero, s(0) is 1, s(s(0)) is 2 and so on.
I tried to write predicate for adding "s numbers":
the predicate s2int convert "s number" to int.
s2int(0, 0).
s2int(s(X), Y) :-
s2int(X, Y1),
Y is 1 + Y1.
add(X, Y, Z) :-
s2int(X, SX),
s2int(Y, SY),
s2int(Z, SZ),
SZ is SX + SY.
When I query add it writes the correct answer but the prompt does not come back.
What's the problem?
Your definition of add/3 works fine, and also terminates, if all three arguments are given. If you leave one of them as a variable, one of the goals s2int(XYZ, SXYZ) has then two uninstantiated variables as arguments. It describes thus an infinitely large set, whose complete enumeration takes infinitely long.
Not sure what you are after, but probably you want to define add/3 for successor arithmetics. You can do this, without resorting to the 0,1,2 integers! Try it! Otherwise search of successor-arithmetics.

Resources