Prolog list of lists get all elements

江枫思渺然 提交于 2019-12-02 20:45:57

问题


I have a lists of lists:

decide([[1,2,-3],[-2,3],[6],[4]],K). 

I want to return all the possible solutions pressing ';'.

The rule is to first return the values that its list has size 1.

Then I want to return the values that its size is bigger than 1.

size([],0).
size([_|Xs],L) :- size(Xs,N),L is N+1.

head([],[]).
head([X|_],X).

return_list_members([X|_], X).
return_list_members([_|T], X):-return_list_members(T, X).


decide([], []).
decide([L|Ls], Lit):- size(L, N), N == 1, head(L, Lit).
decide([L|Ls], Lit):- size(Ls, N), N == 0, head(L, Lit), !.
decide([L|Ls], Lit):- decide(Ls, Lit) ,return_list_members(Ls, Lit)

Example how should be the resulr:

? - decide([[1,2,-3],[-2,3],[6],[4]],K).
K = 6 ;
K = 4 ;
K = -2 ;
K = 3 ;
K = -3 ;
K = 2 ;
K = 1.

My goal is to return first the list with only one value. Then return all the elem of the others lists, one by one. The form I have the code, only return the first elem of the list, because I have the head call. How I can return not only the head values, but all the others, and without repetead? I tried to creat a function for return all the elem of the lists.

Any suggestion?


回答1:


Taking your other question as a starting point, simply insert your new requirements:

listoflist_member(Xss, X) :-
   ( Xs = [_] ; Xs = [_,_|_] ),           % new
   member(Xs, Xss),
   member(X, Xs).


来源:https://stackoverflow.com/questions/50541887/prolog-list-of-lists-get-all-elements

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