Search code examples
recursionprologiteration

how iterate on an empty input in prolog?


i want to know if there are any methods to achieve an iteration in Prolog passing an empty input. For example I would like to have 0 on the first iteration, 1 on the next one, 2 on the second one and so on.


Solution

  • From your comment:

    Example: iterate() is my query and every time i call it i want that the output is 0 first time 1 second time and so on.

    Shouldn't be any more difficult than this:

    increment(N) :- inc(0,1,N).
    
    inc(C , _ , C ) .
    inc(C , S , N ) :- C1 is C+S, inc(C1,S,N).
    

    To break it down, a very common idiom in Prolog programming is the use of helper predicates. Since prolog doesn't have any sort of iteration construct, it just has recursion and backtracking, often to do something useful, you'll need to carry additional state as you go: things like the current value of a counter, etc.

    So . . .

    We have our increment/1 predicate. All it does is invoke a helper predicate, inc/3. It carries, in addition to the variable from the calling predicate (N), two additional pieces of state:

    • The current value (C) of a counter, and
    • The step value (S), that value by which the counter should be incremented in each recursive call.

    Those bits of state are initialized with 0 and 1 respectively.

    inc/3, our helper predicate has just two clauses:

    inc(C , _ , C ) .
    inc(C , S , N ) :- C1 is C+S, inc(C1,S,N).
    

    What it does is this:

    • On initial entry to the predicate, the 1st clause of the predicate is entered, and current value of the counter is unified with N, the desired value, and succeeds.

    • On backtracking, that unification is undone, and the 2nd clause of the predicate is entered. That does the following:

      • The next value (C1) is computed as the sum of the current and step values.
      • inc/3 is recursively invoked, passing C1, S, and N.

    You might note that this predicate is non-terminating: If you were to run inc(0,1,N), writeln(N), fail, your CPU would spin to 100% as it started writing to the console

    0
    1
    2
    3
    4
    . . .