Gilgamesz
Gilgamesz

Reputation: 5073

Parser for simple expression in Prolog

parseExp( ExpToParse, Op(Operand1, Operand2)) :-
    operand(ExpToParse, Diff, Operand1),
    operator(Diff, Diff2, Op),
    operand(Diff2, _, Operand2).

operand([H|L], L, H).
operator(['+'|R], R, add).
operator(['-'|R], R, sub).
operator(['*'|R], R, mul).
operator(['/'|R], R, div).

I am trying to implement parser for simple expressions, I mean something like: 2 + 4 etc.

But, I got the compiler error in the first line:

Syntax error: Operator expected

I cannot understand. I want to the second argument of the first term (Operator(Operand1, Operand2)) will be unified to add( 2, 4). I mean:

parseExp( [2, '+', 4] , X ). ?- X = add(2,4)

I don't undersant why a compiler has a problem.

And the second issue:

I know about DCG but I don't use it now because I as you can see I have a problem with understanding difference list. So, you are welcome to say someting about my code in that context.

Thanks in advance :)

Upvotes: 0

Views: 83

Answers (1)

pasaba por aqui
pasaba por aqui

Reputation: 3529

It is not allowed to write Op(Operand1, Operand2) like in:

parseExp( ExpToParse, Op(Operand1, Operand2)) :- 
  ...

instead, use:

parseExp( ExpToParse, RES) :- 
  ...,
  RES =.. [ Op, Operand1, Operand2 ]

in your example, that means change code to:

parseExp( ExpToParse, RES ) :-
    operand(ExpToParse, Diff, Operand1),
    operator(Diff, Diff2, Op),
    operand(Diff2, _, Operand2),
    RES =.. [Op,Operand1, Operand2]. 

Upvotes: 1

Related Questions