ampl

ampl looping, repeat until loop , syntax error


I just started on ampl and tried some easy algorithm basics . Why is something like this repeat until loop not working ?

param x=8 ;
repeat until x=0;  
    param x=x-1;

display x;

test.mod, line 3 (offset 33): syntax error context: repeat until x=0 >>> ; <<<


Solution

  • The syntax for the repeat until loop in AMPL is the following (see, e.g., page 262 of https://ampl.github.io/ampl-book.pdf):

    param x;
    let x := 8;
    repeat until x == 0 {
        display x;
        let x := x-1;
    }
    display x;
    

    It will produce the following output:

    x = 8
    
    x = 7
    
    x = 6
    
    x = 5
    
    x = 4
    
    x = 3
    
    x = 2
    
    x = 1
    
    x = 0
    

    Note that param x = 8; needs to be replaced by param x; let x := 8; since otherwise you would not be able to change its value.