Reputation: 1
I am writing in Prolog and keep getting the error;
syntax error: current or previous operator needs brackets
When referring to te=he following code:
convert_to_tokens([Word|Rest], [Token|RestTokens]) :-
atom_string(Atom, Word),
( Atom == '+' -> Token = pl
; Atom == '-' -> Token = mi
; Atom == '*' -> Token = ti
; Atom == '/' -> Token = di
; number_string(Number, Word) -> Token = Number
; atom_chars(Word, [H|T]), char_type(H, alpha) -> Token = id(Word)
; Token = Atom
),
convert_to_tokens(Rest, RestTokens).
I have tried using actual brackets, curly brackets, removing the brackets, etc. But I cannot seem to find a solution. Can anyone figure out what it is asking for? Thank you!
Upvotes: 0
Views: 202
Reputation: 74257
I don't see that error. Once I remove your singleton variable warning, it just fails: https://swish.swi-prolog.org/p/chEjJzTM.pl
But if your Prolog is whining about infix (or other) operators like that, just enclose them in parenthesis:
( + )
But wouldn't it be cleaner and more, well, Prolog-like, to do something like this?
https://swish.swi-prolog.org/p/MSlYBdWG.pl
convert_to_tokens( [] , [] ) .
convert_to_tokens( [W|Ws] , [T|Ts] ) :-
atom_string(A, W),
map_token( A, T) ,
!,
convert_to_tokens(Ws,Ts).
map_token( + , pl ) .
map_token( - , mi ) .
map_token( * , ti ) .
map_token( / , di ) .
map_token( A , T ) :- number_atom(A,T) .
map_token( A , id(A) ) :- sub_atom(A,0,1,_,C), char_type(C,alpha).
map_token( A , A ) .
number_atom(N,A) :- atom_number(A,N) .
where
?- convert_to_tokens(
[ "+" , "-" , "*" , "/" , "12345", "alpha" , "!@#" ] ,
Tokens
) .
produces the expected
Tokens = [ pl , mi , ti , di , 12345 , id(alpha) , '!@#' ]
Upvotes: 0
Reputation: 10102
The brackets the error message refers to are round brackets.
In place of Atom == '+'
write Atom == (+)
and same for -
, *
, /
to make it ISO syntax. That specific error message was produced by gnu-prolog.
Also note that the code was probably written for SWI, since e.g. atom_string/2 is not ISO, but is present in SWI. All these conversions are only necessary in SWI btw.
Upvotes: 1