在Prolog中对列表进行分区 [英] Partitioning a List in Prolog
问题描述
我正在尝试创建一个Prolog谓词,在给定一个列表的情况下,可以查看该列表是否可以分为两个总和相同的列表.
I am trying to create a Prolog predicate where, given a list, it is seen whether or not the list can be split into two lists that sum to the same amount.
我有一个工作列表总和谓词,所以我在分区谓词中使用它.我首先尝试对谓词进行编码,以查看列表的第一个元素是否等于列表其余部分的总和([2,1,1]).这就是我要面对的情况.
I have a working list sum predicate, so I am using that within my partitioning predicate. I first tried to code the predicate to see if the first element of the list equals the sum of the rest of the list ([2,1,1]). This is what I have for that situation.
partitionable([X|Y]) :-
sum([X],SUM),
sum([Y],SUM2),
SUM = SUM2.
但是,我收到此错误消息:
However, I am getting this error message:
ERROR: is/2: Arithmetic: `[]/0' is not a function.
我想深入研究递归列表的其余部分,尽管我对此消息的含义感到困惑,因为我还没有写'[]/0' function
,所以我想让这部分工作.感谢您的帮助.
I would like to get this piece working before I delve into the recursion for the rest of the list, though I am confused on what this message is saying, since I have not written a '[]/0' function
. Any help is appreciated.
推荐答案
要将列表划分为两个不重叠的子序列,
我们使用list_subseq_subseq/3
:
To partition a list into two non-overlapping subsequences,
we use list_subseq_subseq/3
:
list_subseq_subseq([] ,[] ,[]).
list_subseq_subseq([X|Xs],[X|Ys],Zs) :-
list_subseq_subseq(Xs,Ys,Zs).
list_subseq_subseq([X|Xs],Ys,[X|Zs]) :-
list_subseq_subseq(Xs,Ys,Zs).
对于执行整数算术,我们使用clpfd :
For performing integer arithmetics, we use clpfd:
:- use_module(library(clpfd)).
让我们把它们放在一起!在下面的示例查询中,我们将列表[1,2,3,4,5,6,7]
分区:
Let's put it all together! In the following sample query we partition the list [1,2,3,4,5,6,7]
:
?- Xs = [1,2,3,4,5,6,7],
sum(Xs,#=,Total),
Half*2 #= Total,
list_subseq_subseq(Xs,Ys,Zs),
sum(Ys,#=,Half),
sum(Zs,#=,Half).
Xs = [1,2,3,4,5,6,7], Total = 28, Half = 14, Ys = [1,2,4,7], Zs = [3,5,6]
; Xs = [1,2,3,4,5,6,7], Total = 28, Half = 14, Ys = [1,2,5,6], Zs = [3,4,7]
; Xs = [1,2,3,4,5,6,7], Total = 28, Half = 14, Ys = [1,3,4,6], Zs = [2,5,7]
; Xs = [1,2,3,4,5,6,7], Total = 28, Half = 14, Ys = [1,6,7] , Zs = [2,3,4,5]
; Xs = [1,2,3,4,5,6,7], Total = 28, Half = 14, Ys = [2,3,4,5], Zs = [1,6,7]
; Xs = [1,2,3,4,5,6,7], Total = 28, Half = 14, Ys = [2,5,7] , Zs = [1,3,4,6]
; Xs = [1,2,3,4,5,6,7], Total = 28, Half = 14, Ys = [3,4,7] , Zs = [1,2,5,6]
; Xs = [1,2,3,4,5,6,7], Total = 28, Half = 14, Ys = [3,5,6] , Zs = [1,2,4,7]
; false.
这篇关于在Prolog中对列表进行分区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!