1

I'm fairly new to prolog and was gven code to modify for homework. However i am stuck with inputting stings. I am aware that strings inputted in prolgo are lists of ascii codes. ie, "abc" = [97, 98, 99]

This is the given code

accept(W) :- start(S), path(S, W).
path(S, []) :- final(S).
path(S, [H|T]) :- arc(S, H, N), path(N, T).
start(1).
final(3).
arc(1, a, 1).
arc(1, b, 2).
arc(2, a, 2).
arc(2, b, 3).
arc(3, a, 3). 

This is a nondeterministic machine, with the knowledge of how strings are implemented, it was my assumption that the changing of the arc() facts to something like

arc(1, 97, 1).
arc(1, 98, 2).
arc(2, 97, 2).
arc(2, 98, 3).
arc(3, 97, 3). 

would enable me to input a string of a's and b's, but that didnt work, can anyone help me with how i would do so? Thank you

Maandeep
  • 97
  • 1
  • 7
  • Also to input, you would write something like accept([list of a's and b's]), this is why i thought strings which are a list of ascii codes, would work with the modified arc. – Maandeep Sep 06 '13 at 03:00

2 Answers2

0

The data types in Prolog are numbers, variables, atoms and compound terms. Conceptually, Prolog thinks of strings as atoms, not lists of character codes. Have a read here for a (little) more detail: http://en.wikipedia.org/wiki/Prolog#Data_types

Also, if you would like to know more about conversion from characters to ASCII codes maybe have a read of this question: Prolog - List of CharCodes to a String or Characters

You can test a list of a's and b's to see if they form a path by giving the predicate a list, for example:

accept([a,a,b,a]).

Hope that helps!

Community
  • 1
  • 1
Peter Hude
  • 101
  • 5
0

you could keep your grammar in the more readable form, and apply a conversion from character code to character:

3 ?- maplist(char_code, W, "aabaabaaa"), accept(W).
W = [a, a, b, a, a, b, a, a, a] 

or

9 ?- read_line_to_codes(user_input, Cs), maplist(char_code, W, Cs), accept(W).
|: abab
Cs = [97, 98, 97, 98],
W = [a, b, a, b] 

otherwise, the syntax for character literals is

arc(1, 0'a, 1).
arc(1, 0'b, 2).
arc(2, 0'a, 2).
arc(2, 0'b, 3).
arc(3, 0'a, 3). 

after that change (or using your numeric representation, arc(1, 97, 1).)

% /home/carlo/prolog/stackoverflow compiled 0.01 sec, 23 clauses
10 ?- read_line_to_codes(user_input, W), accept(W).
|: abab
W = [97, 98, 97, 98] 
CapelliC
  • 59,646
  • 5
  • 47
  • 90