gpt4 book ai didi

Prolog,将列表拆分为两个列表

转载 作者:行者123 更新时间:2023-12-02 01:08:59 25 4
gpt4 key购买 nike

我遇到了列表问题。我需要做的是将一个列表 [1,-2,3,-4] 拆分为两个列表 [1,3][- 2,-4]。我的代码如下所示:

lists([],_,_).
lists([X|Xs],Y,Z):- lists(Xs,Y,Z), X>0 -> append([X],Y,Y) ; append([X],Z,Z).

我得到

Y = [1|Y],
Z = [-2|Z].

我做错了什么?

最佳答案

如果您的 Prolog 系统提供 你可以保留 。想知道怎么做吗? 继续阅读!

我们采用 lists/3 的第二个定义@CapelliC 写的 his answer作为起点,并替换 partition/4通过 tpartition/4 (<)/2通过 (#<)/3 :

lists(A,B,C) :- tpartition(#<(0),A,B,C).

让我们运行一个示例查询!

?- As = [0,1,2,-2,3,4,-4,5,6,7,0], lists(As,Bs,Cs).As = [0,1,2,-2,3,4,-4,5,6,7,0],Bs = [  1,2,   3,4,   5,6,7  ],Cs = [0,    -2,    -4,      0].

As we use monotone code, we get logically sound answers for more general queries:

?- As = [X,Y], lists(As,Bs,Cs).
As = [X,Y], Bs = [X,Y], Cs = [ ], X in 1..sup, Y in 1..sup ;
As = [X,Y], Bs = [X ], Cs = [ Y], X in 1..sup, Y in inf..0 ;
As = [X,Y], Bs = [ Y], Cs = [X ], X in inf..0 , Y in 1..sup ;
As = [X,Y], Bs = [ ], Cs = [X,Y], X in inf..0 , Y in inf..0 .

关于Prolog,将列表拆分为两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28250167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com