1

enter image description here

I am trying to build this program but having a really hard time. So I started off writing this program, I have a long program that almost works but is long and messy. Can anyone give me hints or be able to show me how to write this program in prolog? So for the base case, I figured out that it should be

sum(num(X), num(Y), Z):- Z is X + Y.
prod(num(X), num(Y), Z):- Z is X * Y.

I don't know how to distinguish whether the node is a product node or a sum node when traversing the tree. I do understand that num(X) is the leaf, while prod(X, Y) and sum(X, Y) are nodes.

roy
  • 341
  • 1
  • 2
  • 10
  • 4
    One problem is you're representing your problem incorrectly. You need to focus on an `eval` predicate, which is `eval(Expression, Result)`. `sum` and `prod` are just functors to represent your expression terms. One clause would be, `eval(num(N), N)`. This makes `num(N)` a *leaf* because it doesn't recurse any further and yields `N` as a result. Another clause would be, `eval(sum(X, Y), Result) :- eval(X, XR), eval(Y, YR), Result is XR + YR.`, etc. Prolog will handle everything recursively. – lurker Sep 05 '15 at 02:33
  • and then for product, I would do the same exact thing as well? @lurker – roy Sep 05 '15 at 02:40
  • 3
    If you think about it and try, you'll answer your own question. :) – lurker Sep 05 '15 at 02:42
  • your the boss lurker @lurker. I love you – roy Sep 05 '15 at 03:25

0 Answers0