All partitions of a list in prolog

前端 未结 2 2052
滥情空心
滥情空心 2021-01-20 11:20

I am coding in Prolog. I want to find all distinct partitions of a list. I look at a list as a set here. Each partition is a set of sets in which none is empty, the union of

2条回答
  •  情话喂你
    2021-01-20 11:44

    part([Single], [[Single]]).
    
    part([First|Others], [[First] | Result]) :-
        part(Others, Result).
    
    part([First|Others], Result) :-
        part(Others, Temp),
        addElement(First, Temp, Result).
    

    /* addElement(E, L, R) iff R is the same list of lists as L, except one of its sublist has an extra E in front */

    addElement(Element, [FirstList | OtherLists], 
               [ [Element|FirstList] | OtherLists]).
    addElement(Element, [FirstList | OtherLists], 
               [ FirstList | Temp] )
                  :- addElement(Element, OtherLists, Temp).
    

    Execution:

    ?- part([a,b,c,d],X).
    X = [[a], [b], [c], [d]] ;
    X = [[a], [b], [c, d]] ;
    X = [[a], [b, c], [d]] ;
    X = [[a], [c], [b, d]] ;
    X = [[a], [b, c, d]] ;
    X = [[a, b], [c], [d]] ;
    X = [[b], [a, c], [d]] ;
    X = [[b], [c], [a, d]] ;
    X = [[a, b], [c, d]] ;
    X = [[b], [a, c, d]] ;
    X = [[a, b, c], [d]] ;
    X = [[b, c], [a, d]] ;
    X = [[a, c], [b, d]] ;
    X = [[c], [a, b, d]] ;
    X = [[a, b, c, d]] ;
    false.
    

提交回复
热议问题