I'm very new to Prolog and I'm trying to build a script where I can generate a random string with Prolog. So far I've not had much luck.
My thought for doing this was to generate a list of characters that are required, create a random number based on the size of the list and try and pull a character from that list. This works fine but I also need to be able to concatenate onto a variable which will obviously start out as nothing. For now I am just trying to limit the size of the string to 5 characters but in the future I will want something a bit more complicated (such as between 5 - 8 characters).
Here is what I have so far:
generate :-
Output = '',
generate_random_string(Output, 0),
write(Output).
generate_random_string(Output, 5) :-
Characters = ['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g'],
random(0, 14, RandomValue),
nth0(RandomValue, Characters, RandomCharacter),
append(RandomCharacter, Output, Concat),
Output = Concat.
generate_random_string(Output, CharNum) :-
CharNum \= 5,
Characters = ['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g'],
random(0, 14, RandomValue),
nth0(RandomValue, Characters, RandomCharacter),
append(RandomCharacter, Output, Concat),
Count is CharNum + 1,
Output = Concat,
generate_random_string(Output, Count).
I believe this is breaking around the append call but I'm not really sure why, although I do know it is breaking on the first iteration and it gives a result of false. Any help towards this would be much appreciated.
append/3
.append/3
operates on lists. You might wantatom_concat/3
. – lurker