本文介绍了用于拆分数组的 Prolog 谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当 Res 是一个列表时,谓词 splitEvery(N,List,Res) 成功,其中每个列表List中的N个连续元素被分组在一个保持顺序的列表中
The predicate splitEvery(N,List,Res) succeeds when Res is a list in-which every N consecutive elements in the list List are grouped in a list maintaining the order
示例:
?- splitEvery(2,[a,b,c,d,e,f,g,h],R). R = [[a, b], [c, d], [e, f], [g, h]] ; false. ?- splitEvery(4,[a,b,c,d,e,f,g,h],R). R = [[a, b, c, d], [e, f, g, h]] ; false. ?- splitEvery(8,[a,b,c,d,e,f,g,h],R). R = [[a, b, c, d, e, f, g, h]] ; false.这是我目前正在解决的一个问题,这是我每次都返回的尝试:
That is a problem I am currently working on and that was my attempt that return everytime:
splitEvery(A,L,L):- length(L,A). splitEvery(A,[],[]). splitEvery(A,[H|T],R):- helper(A,B,[H|T],R). helper(A,B,[H|T],R):- B\=0, B=<A, B1 is B-1, helper(A,B1,T,[[H|Z]|R]). helper(A,0,[H|T],R):- helper(A,A,T,[[H|Z]|R]). 推荐答案假设列表必须被分成大小均匀的子列表,一个可能的解决方案是:
Supposing the list must be splitted into evenly sized sublists, a possible solution is:
% split_every(+N, +List, -ListOfLists) split_every(_, [], []). split_every(N, [X|Xs], [Y|Ys]) :- length(Y, N), append(Y, L, [X|Xs]), split_every(N, L, Ys).示例:
?- split_every(2, [1,2,3,4,5,6,7,8], L). L = [[1, 2], [3, 4], [5, 6], [7, 8]] ; false. ?- split_every(4, [1,2,3,4,5,6,7,8], L). L = [[1, 2, 3, 4], [5, 6, 7, 8]] ; false. ?- split_every(3, [1,2,3,4,5,6,7,8,9], L). L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ; false. ?- split_every(4, [1,2,3,4,5,6,7,8,9], L). false.为了避免虚假的选择点,我们可以改变这个谓词的前两个参数的顺序:
To avoid spurious choice points, we can change the order of the first two arguments of this predicate:
% split_every(+List, +N, -ListOfLists) split_every([], _, []). split_every([X|Xs], N, [Y|Ys]) :- length(Y, N), append(Y, L, [X|Xs]), split_every(L, N, Ys).示例:
?- split_every([1,2,3,4,5,6,7,8], 2, L). L = [[1, 2], [3, 4], [5, 6], [7, 8]]. ?- split_every([1,2,3,4,5,6,7,8], 4, L). L = [[1, 2, 3, 4], [5, 6, 7, 8]]. ?- split_every([1,2,3,4,5,6,7,8,9], 3, L). L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. ?- split_every([1,2,3,4,5,6,7,8,9], 4, L). false.更多推荐
用于拆分数组的 Prolog 谓词
发布评论