3

i am a novice in Prolog.Now I want to use Prolog to solve arithmetic expression problems. suppose we have a predicate like this: expr(E,Val,Var,Sol) the first is the expression the second is the value the third one is the variable and the forth one is the result. for example if we ask: expr(3+x,2,x,S)the answer will be S=5 and if we ask expr(5*6,3,x,S) the answer will be S=30 in this case the x doesn't appear in the expression so we just ignore the variable and its value. I want to know how can I implement it,can you guys give me some hints

false
  • 10,264
  • 13
  • 101
  • 209
Lin Jiayin
  • 499
  • 1
  • 6
  • 11
  • I do not quite understand what you actually want to do... Solve equations? Or evaluate arithmetic expressions (with some additional substitution)? – repeat Sep 24 '15 at 05:45

1 Answers1

2
number_si(N) :-
   functor(N,_,_),
   number(N).

expr(V,Val,V,Val).
expr(N, _Val, _Var, N) :-
   number_si(N).
expr(A+B, Val,Var, R) :-
   expr(A, Val, Var, RA),
   expr(B, Val, Var, RB),
   R is RA+RB.

There are even cleaner ways to express this. Maybe someone else wants to contribute.

false
  • 10,264
  • 13
  • 101
  • 209