在 Prolog 中动态拆分列表 [英] Split a list dynamically in Prolog

查看:65
本文介绍了在 Prolog 中动态拆分列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用 prolog 几个星期,但我看到了更深入的操作列表的递归谓词的构造.我的问题是:有可能构建一个将给定列表拆分为给定数量的其他列表的谓词吗?

I started with prolog a few weeks, and yet I'm seeing more deeper the construction of recursive predicates who manipulate lists. My question is: it's possible build a predicat that split a gived list in a given number of other lists?

例如,我想象的:

split([H|T], NumberLists, Lists) -- 递归实现 --

split([H|T], NumberLists, Lists) -- recursive implementation --

?- split([1,2,3,4,5,6,7,8],2,Lists).
Lists = [[1,2,3,4],[5,6,7,8]].

?- split([1,2,3,4,5,6,7,8],4,Lists).
Lists = [[1,2],[3,4],[5,6],[7,8]].

谁能给我一个实现的例子?

Someone can give me an example of implementation?

谢谢!

推荐答案

应该这样做.没有内置谓词:

Something like this ought to do. No built-in predicates:

partition( [] , _ , []       ) .  % the empty list is already partitioned
partition( Xs , N , [Pfx|Ys] ) :- % for a non-empty list, we...
  take(N,Xs, Pfx , Sfx ) ,        % - split it into a prefix of (at most) length N and its suffix.
  partition(Sfx,N,Ys)             % - recursively partition the suffix
  .                               % Easy!

take( 0 , Xs  , []     , Xs  ) .     % if we reach zero, we're done. Close the prefix and hand back whatever is left over.
take( N , []  , []     , []  ) :-    % if we exhaust the source list, we're done. close the prefix and hand back the empty list as the suffix.
  N > 0                              % - assuming, of course, that N is greater than zero.
  .                                  %
take( N , [X|Xs] , [X|Ys] , Sfx ) :- % otherwise prepend the current item to the prefix
  N > 0 ,                            % - assuming N is greater than zero,
  N1 is N-1 ,                        % - then decrement N
  take(N1,Xs,Ys,Sfx)                 % - and recurse down.
  .                                  % Also easy!

这篇关于在 Prolog 中动态拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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