2

I'm trying to generate a list of random length using the lists and clpfd libraries. I've tried the following:

?- use_module(library(clpfd)).
?- use_module(library(lists)).

gen_mem_burst(X) :-
    Len in 1..2,
    length(X, Len).

I see that Prolog first finds a solution with only one list element, then a solution with two elements, just as I expected. Afterwards it issues an 'out of global stack' message. I traced it and I noticed that it keeps trying to set Len to 3, 4, 5, ... and so on. How can I get it to stop?

I'm a Prolog newbie and I'm not even sure if this is a valid use model. In other constraint based languages I've used (e.g. SystemVerilog), this is easily possible.

repeat
  • 18,496
  • 4
  • 54
  • 166
Tudor Timi
  • 7,453
  • 1
  • 24
  • 53

1 Answers1

2

At least with SWI-Prolog, length/2 does not work exactly as expected when constrained variables are involved: I was stuck on the exact same problem. There are several good answers that may give you pointers.

Anyway, answering the title of your question: generating a list of random length:

?- set_random(seed(1)), /* if you want to seed */
   Len is random(9),
   length(L, Len).
Len = 2,
L = [_G2748, _G2751].

If you just need to generate lists of all lengths between two limits,

?- between(1, 3, Len), length(L, Len).

is probably the easiest way to go.

Community
  • 1
  • 1
  • 1
    I think I chose the title poorly. My intention is to be able to generate all possibilities (i,e, lists of length 1 and lists of length 2). I've used the `fd_length(..)` method from your link. – Tudor Timi Sep 29 '15 at 07:46
  • @Tudor Hm, still not sure. Do you absolutely want to use a constrained variable for this? See the update to my answer for a way of doing it without. The `fd_length/2`, as nice as it is, is an overkill if you don't really need to put a proper CLP(FD) constraint on the list length. –  Sep 29 '15 at 07:49
  • 1
    Using `between` is even cooler for my requirements (as I do just need to sweep), but it's good to keep in mind the `fd_length/2` approach should I ever need to add more complicated constraints to a list length. – Tudor Timi Sep 29 '15 at 08:05