Prolog 比较并有条件地返回 true 或 false [英] Prolog comparing and returning true or false conditionally
问题描述
我是 prolog 的新手,正在尝试解决一些问题.我有两个列表,例如 List1 和 List2 下面分别是:
I am new to the prolog and trying to solve some problems. I have two lists for example List1 and List2 respectively below:
List1: [[0.1, 0.6], [0.1, 0.5], [0.3, 0.5]]
List2: [0.2, 0.7, 0.4]
我需要检查 List2
的第 n 个元素是否在 List1
中相应(第 n 个)数字对的范围之间.如果List2
中的数字在范围内,则检查List2
的第(n+1)个元素是否满足相同条件.如果一个数字不满足条件,那么我需要返回 false.如果 List2
中的所有数字都满足条件,那么我需要返回 true.
I need to check if nth element of the List2
is between the range of the corresponding (nth) number pair in the List1
. And if the number in List2
is in the range, then check if the (n+1)th element of the List2
satisfies the same condition. If a number does not satisfy the condition, then I need to return false. If all of the numbers in List2
satisfies the condition, then I need to return true.
我想出了这个主意,但它行不通,我也找不到原因.
I came up with this idea, but it does not work and I could not find why.
bet(L, R, B) :-
Factor1 is B-L,
Factor2 is R-B,
Factor1 > 0,
Factor2 > 0.
comp_lims([], []).
comp_lims([H1|T1], [H2|T2]) :-
member([Left|T], H1),
member(Right, T),
bet(Left, Right, H2) -> comp_lims(T1, T2); fail.
bet
实际上是我为浮点数编写的比较谓词,在如下测试时效果很好:
bet
is actually a comparison predicate i wrote for the floating point numbers and it works fine when testing it like below:
?- bet(0.3, 0.7, 0.4).
true.
?- bet(0.3, 0.7, 0.8).
false.
但是我找不到 comp_lims
谓词有什么问题,我被卡住了.非常感谢您的帮助!
But I cannot find what is wrong with the comp_lims
predicate and I am stuck. A help will be much appreciated!
推荐答案
comp_lims([], []).
comp_lims([H1|T1], [H2|T2]) :-
H1 = [Left, Right],
( bet(Left, Right, H2) -> comp_lims(T1, T2); fail ).
更好的版本:
comp_lims([], []).
comp_lims([ [Left, Right] | T1], [H2|T2]) :-
bet(Left, Right, H2), comp_lims(T1, T2).
- 模式匹配不只是
[Head|Tail]
形式,你可以用[A, B]
来匹配两个元素列表. - 你可以写
A ->乙;失败
和A, Bcode> 一样(也有一个隐含的削减,但你现在可以忽略它).
- Pattern matching need not just be
[Head|Tail]
form, you can just use[A, B]
to match two element lists. - You can write
A -> B; fail
as justA, B
(there is an implicit cut too, but you can ignore it for now).
同样在 bet/3
中,你可以这样做:
Also in bet/3
, you can just do :
bet(L, R, B) :-
B-L > 0,
R-B > 0.
>
隐式计算双方,因此您不需要为它使用单独的 is
.
>
implicitly evaluates both sides, so you do not need to use separate is
for it.
这篇关于Prolog 比较并有条件地返回 true 或 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!