简体   繁体   English

CLP Prolog-逻辑编程

[英]CLP Prolog - Logic Programming

we have a list of list think an example ?- solve([[40,A,B],[30,B],[60,A,B,C]]),label([A,B,C]). 我们有一个列表列表,想想一个例子?- solve([[40,A,B],[30,B],[60,A,B,C]]),label([A,B,C]). will succeed with replacing B=30,A=10 and C=20. 将成功替换B = 30,A = 10和C = 20。 The constraint with this example is A+B=40, A+B+C=60 and generally every variable are in between 0 and 100. Every list must begin with a constant and it includes at least one variable. 此示例的约束为A + B = 40,A + B + C = 60,并且通常每个变量都在0到100之间。每个列表都必须以常量开头,并且至少包含一个变量。

:- use_module(library(clpfd)).

sum([],0).                              % if the list is empty.
sum([X|XS],Z) :-
   sum(XS,Z1),
   X in 0..100,
   Z #= X+Z1.

solveOne([Const|Var]) :-
   sum(Var,Const). 

solve([]).                            % if the list of list is also empty
solve([First|Others]) :-
   solveOne(First),
   solve(Others).

I am a bit skeptic the idea of base case,facts. 我有点怀疑基本情况的想法,事实。 Because every list must include at list one variable according to constraints, on the other hand we think about the "empty list" situation.? 因为每个列表必须根据约束在列表中包含一个变量,另一方面,我们考虑“空列表”的情况。

First, the obvious problem: you define both a solve/2 and a solve/1 predicate ( solve([],0) ). 首先,一个明显的问题:您同时定义了solve/2solve/1谓词( solve([],0) )。 The " ,0 " is probably unwanted. ,0 ”可能是不需要的。

Apart from that, if you have only a constant, like [X] , then solveOne succeeds only if X is zero; 除此之外,如果只有一个常量,例如[X] ,则只有X为零时, solveOne成功; solveOne只有X为零时, solveOne才能成功。 otherwise, it fails according to sum([],0) . 否则,它会根据sum([],0)失败。 So, in a sense, you indirectly check that you can have at least one variable if you assume your sum is always strictly positive. 因此,从某种意义上说,如果您假设总和始终严格为正,则可以间接检查至少可以有一个变量。

In order to explicitely check that there is effectively at least one variable, then you can modify solveOne as follows: 为了明确检查是否至少有一个变量,可以按如下所示修改solveOne

 solveOne([Const,V1|Vars]) :-
    sum([V1|Vars], Const).

@coredump answer should put you on right track. @coredump答案将使您步入正轨。 If you are interested in writing lean code, consider this more succint definition (tested in SWI-Prolog) 如果您对编写精益代码感兴趣,请考虑这个更简洁的定义(在SWI-Prolog中测试)

solve(L) :- maplist(solveOne, L).
solveOne([C|Vs]) :- Vs ins 0..100, sum(Vs, #=, C).

?- solve([[40,A,B],[30,B],[60,A,B,C]]).
A = 10,
B = 30,
C = 20.

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

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