开发者

Prolog Creating A List

I try to create a list from the facts:

mother(jane,jerry).
mother(susan,riche).
mother(helen,kuyt).

I want to convert mothers' names to a list that has a number of elements in it like:

momlist([jane,susan],2).
momlist([jane,susan,helen],3).
momlist([jane],1).

I tried to create this with:

momlist(X,Numbe开发者_运维知识库r):- mom(X,_),
NewNum is Number-1,
NewNum > 0,
write(x),
momlist(X,NewNum).

It just write number times mom's names..

How can I produce a list with these fact?

Best regards and thanks a lot.


Here it is

mother(jane,jerry).
mother(susan,riche).
mother(helen,kuyt).
mother(govno,mocha).
mother(ponos,albinos).

momlist( X, L ) :-
    length( X, L ),
    gen_mum( X ),
    is_set( X ).

gen_mum( [] ).
gen_mum( [X|Xs] ) :-
    mother( X, _ ),
    gen_mum( Xs ).

So

?- momlist(X, 3).
X = [jane, susan, helen] ;
X = [jane, susan, govno] ;
X = [jane, susan, ponos] ;
X = [jane, helen, susan] ;
X = [jane, helen, govno] ;
X = [jane, helen, ponos] ;
X = [jane, govno, susan] ;

And

?- momlist(X, 2).
X = [jane, susan] ;
X = [jane, helen] ;
X = [jane, govno] ;
X = [jane, ponos] ;
X = [susan, jane] ;
X = [susan, helen] ;
X = [susan, govno] ;
X = [susan, ponos] ;
X = [helen, jane] ;

Is that what you want?


A couple of minor problems with the accepted answer:

  1. Adding a second child for a mother (e.g. mother(helen,todd).), will give duplicate results.
  2. gen_mum produces a lot of results that are rejected because they are not a set (e.g. X = [jane, jane,jane]; X=[jane,jane,helen]].

Another possible solution would be:

momlist(X,L):-
    setof(M, C^mother(M,C), AllMoms),
    perm(L, AllMoms, X).

perm(0, _, []):- !.
perm(N, From, [H|T]):-
    select(H, From, NewFrom),
    NewN is N-1,
    perm(NewN, NewFrom, T).

Also if you don't want [jane,helen] aswell as [helen,jane] etc. then you can use subset instead of perm:

subset(0,_,[]):- !.
subset(N, [M|TM], [M|T]):-
    NewN is N-1,
    subset(NewN, TM, T).
subset(N, [_|TM], L):-
    subset(N, TM, L).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜