Code Comments
Programming Forum and web based access to our favorite programming groups.hi all, if i have a file called 'testdata.txt' containing these numbers in the following format: ' 0.1 2.2 4.3 9.6 5.0' for example how do i create a prolog program to copy the data from the text file 'testdata.txt' into a list called 'NewList' in my prolog program??? many thanks
Post Follow-up to this messagePredAlien wrote:
> hi all,
> if i have a file called 'testdata.txt' containing these numbers in
the
> following format:
> ' 0.1 2.2 4.3 9.6 5.0' for example
> how do i create a prolog program to copy the data from the text file
> 'testdata.txt' into a list called 'NewList' in my prolog program???
>
> many thanks
A theoretical point of view:
The request is a program that understand a grammar. A grammar is
understood by a finite state machine. Time for FSMs theory...
OK, I'm lazy. I will simplify the problem to integers. Thus, the input
file can contain:
123 4 56
The grammar is (in grep/perl notation): ( *)([0-9]+)( +))*
So, we have three events: space, digit and eof_of_file:
msg_to_event(48,digit(0)).
msg_to_event(49,digit(1)).
...
msg_to_event(32,space).
msg_to_event(10,space).
msg_to_event(-1,end_of_file).
and two states: s0=reading spaces, s1=reading digits.
Related data for s0 is the list of digits read until now: s0(L).
Related data for s1 is the list of digits and the current integer:
s1(I,L).
Start state is s0 with empty list: s0([]).
Exit will be done if state "exit" is reached.
Then, the fsm rules are:
fsm_rule(s0(L),digit(D),s1(D,L)).
fsm_rule(s1(M,L),digit(D),s1(N,L)) :- N is 10*M+D.
fsm_rule(s0(L),space,s0(L)).
fsm_rule(s1(N,L),space,s0([N|L])).
fsm_rule(s0(L),end_of_file,exit(L)).
fsm_rule(s1(N,L),end_of_file,exit([N|L])
).
Finally, some completion rules (to be adapted to your IO system):
main :-
open('test.dat',read,_FILE,[alias(input)]),
fsm(s0([])).
fsm(exit(L)) :- !,
write(L), nl,
close(input).
fsm(SI) :-
get_byte(input,X),
msg_to_event(X,E),
fsm_rule(SI,E,SO), !,
fsm(SO).
Hope no typo mistakes.
In addition, I suggest to read information about operator "-->"
And, of course, this is not the good way to implement the subject in
real life. But this, this is another history...
Post Follow-up to this messagePowered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.