Prolog Randomness
Skip to end of metadata
Go to start of metadata
Unknown macro: {style}

cite

Unknown macro: {font-family}

When dealing with artificial intelligence that interacts with people, it is useful to introduce some randomness into the system. As usual with prolog, random numbers are generated with predicates.

For example, say you have a list of possible responses. You can randomly choose one as follows.

Unknown macro: {table}
Unknown macro: {tr}
Unknown macro: {td}
Program
getAResponse(Possibilities, Response) :- length(Possibilities, NumPoss), 
                                         random(0, NumPoss,RandomIndex), 
                                         nth0(RandomIndex,Possibilities, Response).
Unknown macro: {td}
Queries
?- getAResponse([howdy,hi,hello,greetings,salutations],Response).
Response = greetings.

?- getAResponse([howdy,hi,hello,greetings,salutations],Response).
Response = hi.

?- getAResponse([howdy,hi,hello,greetings,salutations],Response).
Response = hello.

?- getAResponse([howdy,hi,hello,greetings,salutations],Response).
Response = greetings.

length determines the upper bound for the random number, generated on the next line using random/3 to get an integer within the specified range. Finally nth0 accesses the random index (with indexing beginning at zero).

In other situations, you can use random/1 for a random number between 0 and 1.

The query getAResponse(["hello","howdy","hi","salutations","greetings"],X). will give different results if executed multiple times. A single query only has one response, though. This means that backtracking will not find other possible values for RandomIndex. If it did not act this way, then randomness would be prone to creating infinitely many branches, which is not generally desired behavior.

The random term may be reexecuted, though, if a previous term branched. In the following example, the call is preceded by a clause which has four possible values. Each time, RandomIndex is recomputed, so the the message may be different.

Unknown macro: {table}
Unknown macro: {tr}
Unknown macro: {td}
Program
getAResponse(Possibilities, X,Response) :- length(Possibilities, NumPoss), 
                                         fourOptions(X),
                                         random(0, NumPoss,RandomIndex), 
                                         nth0(RandomIndex,Possibilities, Response).
fourOptions(first).
fourOptions(second).
fourOptions(third).
fourOptions(fourth).
Unknown macro: {td}
Query
?- getAResponse([howdy,hi,hello,greetings,salutations],N,Response).
N = first,
Response = greetings ;
N = second,
Response = greetings ;
N = third,
Response = hello ;
N = fourth,
Response = salutations.

Labels
  • No labels