0

I want to iterate through array in a precondition. But It seems precondition part doesn't allow use of "from" and "across" syntax.

Is there a way to iterate through array in precondition?

insert_last (s: STRING)
require
    new_is_longer_than_prevs:
-- here I want to iterate through array "arr" and if length of s is longer than all other previously stored string values in array
do
    arr.force (s, arr.upper + 1)
end
Miku
  • 41
  • 1
  • 5
  • You are thinking procedurally, but you need to program contracts functionaly. Note: Functional is usually better, even in cases that it is not needed. – ctrl-alt-delor May 30 '18 at 16:48

2 Answers2

1

You can use 'across ... as ... all ... end' or 'across ... as ... some ... end' in precondition and postcondition. The 'all' version is used to valid if a condition is True for every iteration and the 'some' version is used to valid if the condition is True for at least one iteration. You can use some thing like this in your code:

insert_last (s: STRING)
    require
        new_is_longer_than_prevs: 
            across arr.lower |..| arr.upper as la_index all s.count > arr[la_index.item].count end
    do
        arr.force (s, arr.upper + 1)
    end
Louis M
  • 576
  • 2
  • 4
1

The version suggested in the other reply works in most cases (it assumes the lower index of the array is 1). However, the across loop can be used directly on the array rather than on its index range:

new_is_longer_than_prevs:
    across arr as c all s.count > c.item.count end

This version works for any lower index and is slightly more efficient at run-time.

Alexander Kogtenkov
  • 5,770
  • 1
  • 27
  • 35