io - How to read from file using see and putting the content into a list in Prolog? -
i studying prolog using swi prolog , finding many difficulties how read textual data file , printing on screen using see built in predicate.
i have program read content of file using open predicate in read modality , stream associated file
readfile(inputfile, textlist):- open(inputfile, read, stream), readcharacter(stream, textlist), close(stream), !. readcharacter(stream,[]):- at_end_of_stream(stream). %condizione di uscita readcharacter(stream,[char|rest]):- get0(stream,char), readcharacter(stream,rest).
this pretty simple asking if can implement same behavior using see predicate change input stream user (the console) file, , later close stream (coming user) using seen built in predicate:
i thinking this:
readfilesee(inputfile, textlist) :- see(inputfile), read_from_file(textlist), seen. %or maybe: see(user).
but now, differently previous working example, have not stream variable on call get0 predicate, don't know how gon on.
someone can me solve problem reading content of inputfile , putting content textlist list?
edinburgh i/o convenient, bit glitchy because works on principle of screwing around global state. idea use reading , writing predicates take no stream parameter. pretend you're reading standard input or writing standard output. then, before calling code works way, change global input or output stream files want read or write.
so, suppose want read 3 atomic characters. might write:
read_three([a,b,c]) :- get_char(a), get_char(b), get_char(c).
this works standard input:
?- read_three(x). |: abc x = [a, b, c].
to make work file instead, wrap seeing(oldstream), see(filename), ..., seen, see(oldstream)
, code goes in ...
portion. instance, this:
read_three(filename, three) :- % wrapper switch files seeing(oldstream), see(filename), % code read_three(three), % wrapper switch seen, see(oldstream).
using it, need have filename read from, might this:
?- read_three('clone.sh', x). x = [#, !, /].
the key here you're not passing explicit stream instance around, you're relying on predicates implicitly use standard input or output job. in other words, none of predicates should have stream
parameter if they're using edinburgh i/o, nor should using open/3
.
the wrapper writing similar: telling(oldstream), tell(filename), ..., told, tell(oldstream).
Comments
Post a Comment