没有if和else语句的序言 [英] Prolog without if and else statements
问题描述
我目前正在尝试学习一些基本的序言.据我了解,我想远离if else陈述,以真正理解该语言.我在执行此操作时遇到了麻烦.我有一个看起来像这样的简单函数:
I am currently trying to learn some basic prolog. As I learn I want to stay away from if else statements to really understand the language. I am having trouble doing this though. I have a simple function that looks like this:
if a > b then 1
else if
a == b then c
else
-1;;
这只是我想转换为序言的非常简单的逻辑.
This is just very simple logic that I want to convert into prolog.
所以在这里我很困惑.我想先检查a> b,是否输出1.我可以简单地做一下:
So here where I get very confused. I want to first check if a > b and if so output 1. Would I simply just do:
sample(A,B,C,O):-
A > B, 1,
A < B, -1,
0.
这是我想出的. o是输出,但我不知道如何使1为输出.有什么想法可以帮助我更好地理解这一点吗?
This is what I came up with. o being the output but I do not understand how to make the 1 the output. Any thoughts to help me better understand this?
进一步研究之后,我想到了这一点,但这似乎并不正确:
After going at it some more I came up with this but it does not seem to be correct:
Greaterthan(A,B,1.0).
Lessthan(A,B,-1.0).
Equal(A,B,C).
Sample(A,B,C,What):-
Greaterthan(A,B,1.0),
Lessthan(A,B,-1.0),
Equal(A,B,C).
我走了正确的路吗?
推荐答案
您的代码同时存在语法和语义问题.
Your code has both syntactic and semantic issues.
谓词以小写开头,逗号表示一个连词.也就是说,您可以将子句读为
Predicates starts lower case, and the comma represent a conjunction. That is, you could read your clause as
sample(A,B,C,What) if
greaterthan(A,B,1.0) and lessthan(A,B,-1.0) and equal(A,B,C).
然后请注意,What
参数是无用的,因为它没有值-称为单例.
then note that the What
argument is useless, since it doesn't get a value - it's called a singleton.
一种书写析取关系的可能方法(即OR)
A possible way of writing disjunction (i.e. OR)
sample(A,B,_,1) :- A > B.
sample(A,B,C,C) :- A == B.
sample(A,B,_,-1) :- A < B.
请注意测试A < B
,以保护值-1
的分配.这是必要的,因为Prolog将在需要时执行 all 子句.迫使Prolog避免我们不知道不应该完成的某些计算的基本结构是cut
:
Note the test A < B
to guard the assignment of value -1
. That's necessary because Prolog will execute all clause if required. The basic construct to force Prolog to avoid some computation we know should not be done it's the cut
:
sample(A,B,_,1) :- A > B, !.
sample(A,B,C,C) :- A == B, !.
sample(A,B,_,-1).
无论如何,即使您在学习时,我也认为您应该使用if/then/else语法.
Anyway, I think you should use the if/then/else syntax, even while learning.
sample(A,B,C,W) :- A > B -> W = 1 ; A == B -> W = C ; W = -1.
这篇关于没有if和else语句的序言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!