简体   繁体   中英

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,Number):- 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 (eg mother(helen,todd).), will give duplicate results.
  2. gen_mum produces a lot of results that are rejected because they are not a set (eg 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM