N.W.
N.W.

Reputation: 373

Prolog - how to generate list of specific length?

I'm doing this exercise for which I have to write a predicate randomnames/1 for generating a random list of three names (no duplicates allowed). I have a database with 10 names in it already and they all correspond to a number, for example: name(1, Mary). I wrote a predicate for generating one random name:

randomname(Name) :- 
   random(0, 11, N),    % generate random integer between 1 and 10.
   name(N, Name). 

My question would be: How do I get this in a list? And a list of exactly three elements at that? I don't want to use too many built-ins. length/2 would be alright though. I think I might need it :)

Thanks a lot!

Edit: I figured I would first try to generate a list of three random numbers (the names can come later). I wrote this horribly wrong little thing:

numberlist([N|T]) :-
   random(0, 11, N),
   length([N|T], 3),
   numberlist(T).

I know how to do this with a /2 predicate; when the user can just enter in the query that they want a list with three elements (numberlist(3,X).for example). But I'm can't seem to figure out how to write down in code that I always want a list of three numbers. I was also thinking of using findall for generating my list, but again I don't know how to limit the length of the list to three random elements.

Upvotes: 3

Views: 1300

Answers (1)

mat
mat

Reputation: 40768

When describing lists in Prolog, it is often useful to first describe how a single element looks like.

For example, in your case, it seems you already have a predicate like random_name/1, and it describes a single element of the list you want to describe.

So, to describe a list consisting of three such elements, what about:

random_names([A,B,C]) :-
        random_name(A),
        random_name(B),
        random_name(C).

This describes a list with three elements, and random_name/1 holds for each of these elements.

Upvotes: 2

Related Questions