Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

solution to eval(Expr, Value).

Status
Not open for further replies.

mizt

Programmer
Feb 26, 2002
2
GB
Hi

I found this question in a book but it didn't have a solution to it, any have any pointers on how to go about solving it?

Heres the problem

Define evaluate(Expr, Value) that given an arithmetic expression "Expr" in prefix form with binary operations "add" and "mult" standing for addition and multiplication.
evaluate will return the Value of that expression.

eg evaluate( mult(3, add(mult(4,2), add(1,9))), Value).
Value = 54

Any ideas?..

I could do this with a stack in C pretty easily but i find it hard to think in terms of logic.

Thanks for any help you can give. Euan
 
I don't think the following is the best program but...

evaluate(X, V) :- number(X), V is X.
evaluate(mult(X, Y), V) :- evaluate(X, X2), evaluate(Y, Y2), V is X2 * Y2.
evaluate(add(X, Y), V) :- evaluate(X, X2), evaluate(Y, Y2), V is X2 + Y2.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top