prolog

# Prolog - writing a query to calculate total of four given numbers

First off, let me say that I am quite a beginner in Prolog. I can create simple rules and facts (I know how to, for example, recursively define the predecessor relation etc).

However, now I am given a problem where I am given four numbers 40, 10, 12, 30 and I need to add them via two rules (these numbers actually represent electrical resistances). I have these two rules:

``````series(R1,R2,Re) :- Re is R1 + R2.
parallel(R1,R2,Re) :- Re is ((R1 * R2) / (R1 + R2))
``````

40 and 10 need to be added via the parallel rule, the total of them then needs to be added to 12 via the series rule, the sum of which needs to be added to 30 via the parallel rule.

I am completely stumped by how to do this. I have two main questions.

1. Is there any way I can somehow calculate all the sums (up until the last one) in the list of facts and rules (same as when I would, for example, define that Ann is the mother of Tom by writing the fact mother(ann, tom). ), and then write a single query which would be the last calculation (which is parallel of 30 and the other result, let's call it Rx), which would look like this:
``````parallel(30,Rx,X).
``````

Where of course Rx would be a numerical value. I know that if I input a query of this kind, I get the result as output.

1. If not, what's the easiest way to understand how this would work?

Solution

• 40 and 10 need to be added via the parallel rule, the total of them then needs to be added to 12 via the series rule, the sum of which needs to be added to 30 via the parallel rule.

These steps become this code:

``````some_rule_name_here(Answer) :-
parallel(40, 10, Step1),
series(Step1, 12, Step2),
``````?- some_rule_name_here(X).