0

I have the following Prolog program:

father(person1,person2).
mother(person3,person2).

 say_hi(X) :- father(X,person1) , write('Hello1').
 say_hi(X) :- father(X,person2) , write('Hello2').

I want to have a list of different sentences: the program should return different sentences each time that you call say_hi

So , the expected output of the program should be:

 ?- say_hi(person1)
 Hello1
 ?- say_hi(person1)
 Hello3
 ?- say_hi(person4)
 Hello4

The different elements of the list should be written in a random way

3 Answers 3

1

If you want just once each list' element, here is a possible definition (in SWI-Prolog), that returns elements on backtracking:

get_random([E], E) :- !.
get_random(L, E) :-
    length(L, C),
    R is random(C),
    length(Skip, R),
    append(Skip, [X|Tail], L),
    ( E = X
    ; append(Skip, Tail, Rest),
      get_random(Rest, E) ).

test:

?- get_random([a,b,c,d,e,f],X).
X = e ;
X = f ;
X = d ;
X = b ;
X = c ;
X = a.
1
Persons = [person1, person2, person3, person4],
length(Persons, N),
I is random(N),
nth0(I, Persons, P).

will unify P with a random element from the list Persons (in SWI-Prolog).

1

You can make ir with maybe http://www.swi-prolog.org/pldoc/man?predicate=maybe%2f1 But I couldn't manage it to work. So I've made my own maybe predicate:

maybe(P):-
    random(N),
    N<P.

maybe :- maybe(0.5).

I couldn't understand your initial code, so I've changed it a little.

say_hi :- maybe, write('Hello1').
say_hi :- write('Hello2').


?- say_hi.
Hello2
true.

?- say_hi.
Hello1
true .

?- say_hi.
Hello2
true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.