简体   繁体   English

Prolog-递归计算

[英]Prolog - Recursive calculation

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. 您好:)我在编写一个谓词时遇到了一些困难,该谓词对于3个元素的列表-[Operator,Val_A,Val_B],它给了我运算结果。 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: 但是同时Val_A或Val_B可以是具有相同格式的列表,并且应该给出结果:

?-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. ,并且我已经能够为2个数字执行此“计算”谓词,但对于更复杂的列表,我无法做到。 Could you help me? 你可以帮帮我吗?

The key here is to make sure you don't call operate until you have numbers for arguments; 这里的关键是要确保在有参数数字之前不要调用operate 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).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM