Hi prologers,
I don't know if this is kind of a basic question, but I cannot figure it out myself...
The following program:
%% 1.23 (**) Extract a given number of randomly selected elements from a list.
%% Signature:
%% - select(Output, HowMany, Input).
select(Output, HowMany,Input) :- length(Output, HowMany).
select([X|Output], HowMany, Input) :- length(Input, L), random(L, TakeThis), remove(Input2, TakeThis, Input), HowMany1 is HowMany - 1, select(Output, HowMany1, Input2).
%% 1.20 (*) Remove the K'th element from a list.
remove(X, Kth, Y) :- remove(X, Kth, 1, Y).
remove(Xs, Kth, Count, [X|Xs]) :- Kth =:= Count.
remove([X|Zs], Kth, Count, [X|Xs]) :- Kth \= Count, remove(Zs, Kth, Count + 1, Xs).
When I execute:
35 ?- select(X, 1, [a,b,c,d,e,f]).
X = [_G504] .
34 ?- select(X, 3, [a,b,c,d,e,f]).
X = [_G504, _G507, G510] .
When I was expecting selecting 3 random elements from the list.
I guess the error is in the longest line of the program, but I cannot see why it does not manage to instantiate the variables. Can anyone see it?
Thanks!
B.
I don't know if this is kind of a basic question, but I cannot figure it out myself...
The following program:
%% 1.23 (**) Extract a given number of randomly selected elements from a list.
%% Signature:
%% - select(Output, HowMany, Input).
select(Output, HowMany,Input) :- length(Output, HowMany).
select([X|Output], HowMany, Input) :- length(Input, L), random(L, TakeThis), remove(Input2, TakeThis, Input), HowMany1 is HowMany - 1, select(Output, HowMany1, Input2).
%% 1.20 (*) Remove the K'th element from a list.
remove(X, Kth, Y) :- remove(X, Kth, 1, Y).
remove(Xs, Kth, Count, [X|Xs]) :- Kth =:= Count.
remove([X|Zs], Kth, Count, [X|Xs]) :- Kth \= Count, remove(Zs, Kth, Count + 1, Xs).
When I execute:
35 ?- select(X, 1, [a,b,c,d,e,f]).
X = [_G504] .
34 ?- select(X, 3, [a,b,c,d,e,f]).
X = [_G504, _G507, G510] .
When I was expecting selecting 3 random elements from the list.
I guess the error is in the longest line of the program, but I cannot see why it does not manage to instantiate the variables. Can anyone see it?
Thanks!
B.