Problem while reading backslash in Prolog

I am writing a lexer in Prolog to be used as part of a functional language interpreter. The language specification allows expressions such as let \x = x + 2;

. What I want lexer to do for such input is "return":

[tokLet, tokLambda, tokVar(x), tokEq, tokVar(x), tokPlus, tokNumber(2), tokSColon] 

      

and the problem is that Prolog seems to ignore the character \

and "return" the string written above except tokLambda

.

One approach to solving this question would be to somehow add a second backslash before / after each occurrence of one in the program code (because everything works fine if I change the original input to let \\x = x + 2;

), but to me it really is I do not like,

Any ideas?

EDIT: If anyone should have similar problems, then how I solved it:

main(File) :-
  open(File,read,Stream),
  read_stream_to_codes(Stream, Codes),
  lexer(X,Codes,[]),
    ... invoke other methods

      

+2


a source to share


1 answer


Where did you get the string let \x = x + 2;

from?

  • If it's in your Prolog program: yes, you need to double the backslash.
  • If it's from an external file: how do you read it? Perhaps this predicate specifically interprets backslashes.

I was inspired by this problem and wrote some code that should be portable across all Prolog implementations:



% readline(-Line)
%
% Reads one line from the current input. The line is then returned as a list
% of one-character atoms, excluding the newline character.
% The returned line doesn't tell you whether the end of input has been reached
% or not.
readline(Line) :-
    'readline:read'([], Reversed),
    reverse(Line, Reversed).

'readline:read'(Current, Out) :-
    get_char(C), 'readline:append'(C, Current, Out).

'readline:append'(-1, Current, Current) :- !.
'readline:append'('\n', Current, Current) :- !.
'readline:append'(C, Current, Line) :-
    'readline:read'([C | Current], Line).

      

I tried it and it worked for me.

Of course, as explained in question 1846199 , you can also use read_line_to_codes/2

.

+1


a source







All Articles