Last active
October 6, 2020 20:28
-
-
Save smithcommajoseph/f40553e7f047456b1e93cfc50b7e1552 to your computer and use it in GitHub Desktop.
A simple DFA implemented in Prolog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dfa_start(dfa1, q0). | |
dfa_final(dfa1, q3). | |
dfa_transition(dfa1, q0, '0', q1). | |
dfa_transition(dfa1, q0, '1', q1). | |
dfa_transition(dfa1, q0, '.', q2). | |
dfa_transition(dfa1, q1, '0', q1). | |
dfa_transition(dfa1, q1, '1', q1). | |
dfa_transition(dfa1, q1, '.', q3). | |
dfa_transition(dfa1, q2, '0', q3). | |
dfa_transition(dfa1, q2, '1', q3). | |
dfa_transition(dfa1, q2, '.', q4). | |
dfa_transition(dfa1, q3, '0', q3). | |
dfa_transition(dfa1, q3, '1', q3). | |
dfa_transition(dfa1, q3, '.', q4). | |
dfa_transition(dfa1, q4, '0', q4). | |
dfa_transition(dfa1, q4, '1', q4). | |
dfa_transition(dfa1, q4, '.', q4). | |
allStates(DFA, States) :- | |
findall([F,T], dfa_transition(DFA, F, _, T), Transitions), | |
flatten(Transitions, FlatTransitions), | |
list_to_set(FlatTransitions, States). | |
dfaAccept(DFA, InputStr) :- | |
dfa_start(dfa1, CurrentState), | |
string_to_list(InputStr, StrList), | |
dfaAccept(DFA, StrList, CurrentState), | |
!. | |
dfaAccept(DFA, [H|T], CurrentState) :- | |
char_code(Letter, H), | |
dfa_transition(DFA, CurrentState, Letter, NextState), | |
% format('DFA: ~w, CurrentState: ~w, Letter: ~w, NextState: ~w', [DFA, CurrentState, Letter, NextState]), nl, | |
dfaAccept(DFA, T, NextState). | |
dfaAccept(DFA, [ ], CurrentState) :- | |
% format('LastState: ~w', [CurrentState]), nl, | |
dfa_final(DFA, CurrentState), | |
!. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
?- [dfa].
true.
?- dfaAccept(dfa1, '1.0').
true.
?- dfaAccept(dfa1, '1.0.1').
false.