Assertions in design by contract: Difference between revisions

m
m (Automated syntax highlighting fixup (second round - minor fixes))
m (→‎{{header|Wren}}: Minor tidy)
 
(4 intermediate revisions by one other user not shown)
Line 343:
}
(...)</syntaxhighlight>
 
=={{header|jq}}==
{{libheader|Jq/assert.jq}}
{{works with|jq}}
 
jq does not currently support assertions natively though they (and
design by contract) can be simulated as here, using a jq module.
 
The [https://gist.github.com/pkoppstein/9b0f49a213a5b8083bab094ede06652d "assert.jq"] module
allows assertion checking to be turned on or off; in addition,
execution can be continued or terminated after an assertion violation is detected.
 
In the following, it is assumed the "debug" mode of assertion checking has been used, e.g.
via the invocation: jq --arg assert debug
 
This mode allows execution to continue after an assertion violation has been detected.
<syntaxhighlight lang="jq">
include "rc-assert" {search: "."}; # or use the -L command-line option
 
def averageOfAbsolutes:
. as $values
# pre-condition
| assert(type == "array" and length > 0 and all(type=="number");
"input to averageOfAbsolutes should be a non-empty array of numbers.")
| (map(length) | add/length) as $result
# post-condition
| assert($result >= 0;
$__loc__ + { msg: "Average of absolute values should be non-negative."} )
| $result;
 
[1, 3], ["hello"]
| averageOfAbsolutes
</syntaxhighlight>
{{output}}
Invocation: jq -n --arg assert debug -f assertions.jq
<pre>
2
["DEBUG:","assertion violation @ input to averageOfAbsolutes should be a non-empty array of numbers. => false"]
5
</pre>
 
=={{header|Julia}}==
Line 787 ⟶ 827:
{{libheader|Wren-assert}}
Wren doesn't support assertions natively though they (and design by contract) can be simulated using a library.
<syntaxhighlight lang="ecmascriptwren">import "./assert" for Assert
import "./math" for Nums
 
// Assert.disabled = true
9,483

edits