Calc/2 谓词 [英] Calc/2 predicate
问题描述
我需要定义一个谓词calculator/2
,它接受一个英文算术表达式列表并产生一个数字结果.系统应该能够处理数字 1-20.
I need to define a predicate calculator/2
that takes a list of English arithmetic expressions and yields a numerical result. The system should be able to handle numbers 1-20.
执行示例:
?- calculator([three,times,two],Total).
Total=6
yes
?- calculator([twenty,times,three,plus,five,divided_by,two], Total).
Total = 32.5
推荐答案
对于那些说这是我第一次体验序言,我什至不知道从哪里开始"的人来说,这是一项极其艰巨的任务.
This is an extremely hard task for somebody who said "This is my first time experiencing prolog and I don't even know where to start."
我会给你一些开始,但你真的需要学习一些 Prolog 教程(我发现现在学习 Prolog",@mbratch 在评论中提到,非常好)才能做到任务.
I'll give you some things to start, but you really need to work through some Prolog tutorials (I've found 'Learn Prolog Now', mentioned by @mbratch in the comments, very good) to be able to do the task.
首先,你可以定义一些关于数字名称的 Prolog 事实(因为你只需要处理数字 1-20,你可以简单地列举所有的可能性):
First, you can define some Prolog facts about number names (since you only have to handle only numbers 1-20, you can simply enumerate all he possibilities):
number(one, 1).
number(two, 2).
...
number(twenty, 20).
然后您可以定义一些仅适用于两个数字的谓词:
Then you can define some predicates that work for just two numbers:
calculator([A, plus, B], Result) :-
number(A, ValA), number(B, ValB), Result is ValA + ValB.
calculator([A, times, B], Result) :-
number(A, ValA), number(B, ValB), Result is ValA * ValB.
从您的示例来看,没有使用运算符的优先规则.然后如果列表包含超过 2 个数字(超过 3 个条目),您可以将上述谓词应用于前三个列表条目,并递归进行.
Judging from your example precedence rules of the operators are not used. Then if the list contains more than 2 numbers (more than 3 entries), you can apply above predicates to the first three list entries, and proceed recursively.
希望您在完成一些 Prolog 教程后可以从这里继续.
Hope you can continue from here after working through some Prolog tutorials.
这篇关于Calc/2 谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!