Dear Everyone. When I was solving the below constraint(Powers of 2) I got this doubt. I was taught that constraints are declarative not procedural.(i.e we can only check if a statement can be true or false, but cannot assign any value). I am a bit lost in thought after solving the below constraint as I have mentioned the size of the array and also made the first value as 1. How come it is declarative just because I have used a “==” operator? It looks like an assignment operation done for the size of array and making first value as 1. Similar case with “foreach”. How come a loop be declarative? Could anyone shed some light on this , so that whenever I solve any constraint I can have a good mental map?
class prac;
rand int arr[];
//created an array of size 15 and made the first value as 1.
constraint c1{arr.size() == 15;
arr[0] == 1;}
//this constraint finds the powers of 2 by multiplying the previous value by 2
constraint c2{foreach(arr[i])
if(i != 0)
arr[i] == 2*arr[i-1];}
endclass
module tb;
prac p;
initial begin
p = new;
p.randomize();
$display("arr=%0p",p.arr);
end
endmodule
Result:
arr='{1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384}
In Constraints, declarative means you describe what must be true, not how to make it true. The == operator inside constraints represents logical equality, not assignment, so everything written inside a constraint is a logical condition. The constraint solver conceptually considers the space of all possible values for randomizable variables. The constraints you specify restrict that space, enforcing which combinations of values are legal for the given scenario. The solver then selects a solution that satisfies all constraints simultaneously, without executing them step by step or in any order. You don’t need loops to randomize an array unless you need to constraint its elements when the size is unknown.
Your equality operator == example looks like an assignment because one operand is a constant, not anything to solve for.
But take these two equations:
x == y−2;
y == 2*x;
Although there’s only one solution to this problem , you can’t execute these as procedural assignments; they must be solved as simultaneous or declarative equations.
The foreach constraint (as well as if-else) uses a syntax similar to procedural statements. Both serve as a way if instantiating declarative equations. However, foreach imposes a specific order of solving. Before attempting to solve any of the equations it instantiates, the size of the array must be chosen.
1 Like