Hello :) I'm having some difficulties in programming a predicate which for a list of 3 elements - [Operator,Val_A,Val_B], it give me the result of the operation. For example:
?-calc([*,3,2],Res).
Res=6
But at the same time Val_A or Val_B can be a list with the same form, and it should give the result:
?-calc([*,[+,2,4],5],Res).
Res=30 ----->([*,6,5]=30)
?-calc([+,[+,2,[-,4,3]],[*,2,4]],Res).
Res=11 ----->([+,[+,2,1],8]=[+,3,8]=11)
I already have the predicate to calculate the operation between 2 numbers:
operate(Op,[H|T],Res):-
Op == + -> Res is H+T;
Op == - -> Res is H-T;
Op == * -> Res is H*T;
Op == / -> Res is H/T.
, and I'm already able to do this "calc" predicate for 2 numbers, but for more complex list I can't. Could you help me?
The key here is to make sure you don't call operate
until you have numbers for arguments; so something like this:
calc([Op, A1, A2],Res) :-
calc(A1,R1),
calc(A2,R2),
operate(Op,[R1,R2],Res).
The problem, of course, is that you don't have a base case. What is the simplest expression you could have? One that doesn't involve any operator, and is just a number:
calc(N,N) :- number(N).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.