用于拆分数组的 Prolog 谓词

编程入门 行业动态 更新时间:2024-10-06 19:31:29
本文介绍了用于拆分数组的 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 谓词

本文发布于:2023-11-30 15:23:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650496.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:谓词   数组   Prolog

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!