在 Prolog 中对列表进行分区 [英] Partitioning a List in Prolog

查看:17
本文介绍了在 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'函数.任何帮助表示赞赏.

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).

为了执行整数运算,我们使用 :

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆