Prolog: Generating Every Possibility of a List Given a Pattern

久未见 提交于 2019-12-24 16:14:48

问题


Let's say you have a list in Prolog such as: [3,4,2,2,1,4]. How would one go about generating a list of lists of all possible patterns that start at the first element of the list, then either go to the i + 2th element, or the i + 3rd element, and so on from there.

Example: Say I have [3,4,2,2,1,4,8]. I want to be able to generate a list of lists such as: [[3,2,1,8], [3,2,4], [3,2,8]]

I.e. all possibilities of either every other element or every i+3 element, or any other combination, such as i+2,i+3,i+2,i+2, etc.

I've implemented my own version of a powerset, but I can't seem to figure out where to start.


回答1:


gen([], []).
gen([A], [A]).
gen([A, _ | T], [A | Xs]) :- gen(T, Xs).
gen([A, _, _ | T], [A | Xs]) :- gen(T, Xs).

results in

?- gen([3,4,2,2,1,4,8], X).
X = [3, 2, 1, 8] ;
X = [3, 2, 1] ;
X = [3, 2, 4] ;
X = [3, 2, 4] ;
X = [3, 2, 8] ;
false.

You can use findall/3 to get all results

?- findall(X, gen([3,4,2,2,1,4,8], X), Z).
Z = [[3, 2, 1, 8], [3, 2, 1], [3, 2, 4], [3, 2, 4], [3, 2, 8]].


来源:https://stackoverflow.com/questions/36579234/prolog-generating-every-possibility-of-a-list-given-a-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!