如何使用clpfd和lambda?
:- use_module(library(clpfd)).
:- use_module(library(lambda)).
我們定義split/3
這樣的:
split(Xs,N,Yss) :-
length(Xs,L),
N #=< L,
[L0,L1] ins 1..sup,
L0 #= L/N,
L1 #= L - L0*(N-1),
% enumerate `N` *now* if domain is finite.
% ideally, length/2 does something like this (by itself).
(fd_size(N,Size),integer(Size) -> indomain(N) ; true),
length(Yss,N),
append(Yss0,[Ys],Yss), % creates useless choicepoint
maplist(\Ls^length(Ls,L0),Yss0),
length(Ys,L1),
append(Yss,Xs). % note we use append/2 here, not append/3
首先,查詢OP了:
?- split([1,2,3,4,5,6,7,8],2,Lists).
Lists = [[1,2,3,4], [5,6,7,8]]
; false.
?- split([1,2,3,4,5,6,7,8],4,Lists).
Lists = [[1,2], [3,4], [5,6], [7,8]]
; false.
然後,一個更普遍的例子:
?- split([1,2,3,4,5,6,7,8],N,Lss).
N = 1, Lss = [[1,2,3,4,5,6,7,8]]
; N = 2, Lss = [[1,2,3,4], [5,6,7,8]]
; N = 3, Lss = [[1,2], [3,4], [5,6,7,8]]
; N = 4, Lss = [[1,2], [3,4], [5,6], [7,8]]
; N = 5, Lss = [[1], [2], [3], [4], [5,6,7,8]]
; N = 6, Lss = [[1], [2], [3], [4], [5], [6,7,8]]
; N = 7, Lss = [[1], [2], [3], [4], [5], [6], [7,8]]
; N = 8, Lss = [[1], [2], [3], [4], [5], [6], [7], [8]]
; false.
**有人可以給我一個實現的例子嗎?**不,你給我們你試過的,我們會幫你的! – joel76
不要自己編寫遞歸代碼,而應考慮使用buitin /庫謂詞的組合。 – repeat
@repeat提示:'split(L,N,S): - length(S,N),append(S,L).' – CapelliC