1
votes

I am working on a tokenizer in prolog, and i keep getting the following error when attempting to open a file and pass the stream into a predicate: ERROR: at_end_of_stream/1: stream `(0x7fe83d800090)' does not exist. I am attempting to open a file "ass3IN" with the following query:?- tokenizer('ass3IN',A). I have been trying to solve this for a while and any help would be greatly appreciated. Thanks in advance.

  1 tokenizer(File,_) :-
  2    open(File,read,Str),
  3    getchars(Str,Tokenlist),
  4    close(Str),
  5    unifywhitespace(Tokenlist,Newlist),
  6    rem_consec_white(_,Newlist,No2white).
  7 
  8 getchars(Stream,_) :-
  9    at_end_of_stream(Stream).
 10 
 11 getchars(Stream,List) :-
 12    \+ at_end_of_stream(Stream),
 13    get0(Stream,C),
 14    append(List,[C],List1),
 15    getchars(Stream,List1).
1
add a example and expected resultAns Piter
the code is incomplete, as such there is no expected result. i am just having trouble opening a file and using the streamhoya

1 Answers

2
votes

The problem occurs because of backtracking. at_end_of_stream is being backtracked to while your stream is already closed. This reproduces your error:

?- open('/home/some/file',read,S), \+ at_end_of_stream(S), close(S),
   at_end_of_stream(S).

   <stream>(0x2412e50)
   ERROR: at_end_of_stream/1: stream `<stream>(0x2412e50)' does not exist

I guess the absolute quickest way to solve this would be to add a cut (!) after your call to getChars in tokenizer, like so:

tokenizer(File,_) :-
    open(File,read,Str),
    set_input(Str),
    getchars(Str,Tokenlist),!,
    close(Str).

Now the backtracking will no longer occur and your execution will terminate successfully.