Assertions
From Rosetta Code
Show an assertion in your language by asserting that an integer variable is equal to 42.
[edit] Ada
Using pragma Assert:
pragma Assert (A = 42, "Oops!");
The behavior of pragma is controlled by pragma Assertion_Policy. Another way is to use the predefined package Ada.Assertions:
with Ada.Assertions; use Ada.Assertions;
...
Assert (A = 42, "Oops!");
The procedure Assert propagates Assertion_Error when condition is false.
[edit] ALGOL 68
The "Revised Report on the Algorithmic Language - ALGOL 68" suggest that ASSERT may be made available by a particular implementation, quote: "Pragmats may ... convey to the implementation some piece of information affecting some aspect of the meaning of the program which is not defined by this Report,..."
Example given[1]:
INT a, b; read((a, b)) PR ASSERT a >= 0 & b > 0 PR;
This works with neither ELLA ALGOL 68 nor ALGOL 68G.
The standard alternative would be to implement the assertions as an exception as per the Exceptions sample code.
In ELLA ALGOL 68 the ASSERT is implemented as an operator in the environment prelude:
OP ASSERT = (VECTOR [] CHAR assertion,BOOL valid) VOID:
IF NOT valid
THEN type line on terminal(assertion);
terminal error( 661 {invalid assertion } )
FI;
And can be "USEd" as follows:
PROGRAM assertions CONTEXT VOID
USE standard,environment
BEGIN
INT a := 43;
"Oops!" ASSERT ( a = 42 )
END
FINISH
[edit] AutoHotkey
if (a != 42)
{
OutputDebug, "a != 42" ; sends output to a debugger if connected
ListVars ; lists values of local and global variables
Pause ; pauses the script, use ExitApp to exit instead
}
[edit] C
#include <assert.h>
int main(){
int a;
/* ...input or change a here */
assert(a == 42); /* aborts program when a is not 42 */
return 0;
}
[edit] C++
Translation of: C
#include <cassert> // assert.h also works
int main()
{
int a;
// ... input or change a here
assert(a == 42); // Aborts program if a is not 42, unless the NDEBUG macro was defined
// when including <cassert>, in which case it has no effect
}
Note that assert does not get a std:: prefix because it's a macro.
[edit] C#
using System.Diagnostics;
Debug.Assert(a == 42);
[edit] Clojure
(assert (= i 42))
[edit] Common Lisp
(let ((x 42))
(assert (and (integerp x) (= 42 x))))
[edit] D
import std.string;
void main() {
int a = readln().chomp().atoi();
assert(a == 42, "You did not input 42!");
}
[edit] E
E does not have the specific feature of assertions which may be disabled by a global option. But it does have a utility to throw an exception if a condition is false:
require(a == 42) # default message, "Required condition failed"
require(a == 42, "The Answer is Wrong.") # supplied message
require(a == 42, fn { `Off by ${a - 42}.` }) # computed only on failure
[edit] Eiffel
Works with: SmartEiffel version 2.4
There are many assertion types in Eiffel, one is the following:
File called main.e:
class MAIN
creation main
feature main is
local
test: TEST;
do
create test;
io.read_integer;
test.assert(io.last_integer);
end
end
Another file called test.e:
class TEST
feature assert(val: INTEGER) is
require
val = 42;
do
print("Thanks for the 42!%N");
end
end
[edit] Erlang
Erlang doesn't have an assert statement. However, it is single assignment, and its assignment operator won't complain if you reassign the exact same value to an existing variable but will throw an exception otherwise.
1> N = 42.
42
2> N = 43.
** exception error: no match of right hand side value 43
3> N = 42.
42
4> 44 = N.
** exception error: no match of right hand side value 42
5> 42 = N.
42
As such, the behavior of Erlang's assignment operator is extremely similar to a regular assert in other languages.
[edit] Factor
Throw an exception if the value on the top of the stack is not equal to 42:
USING: kernel ;
42 assert=
[edit] F#
F# provides an assert function that is only enabled when the program is compiled with DEBUG defined.
let f x =
assert (x > 1)
x
[edit] Groovy
def doSomething = { x, f ->
assert f != null : "f was null!"
assert f instanceof Closure : "f was not a closure! f: ${f}"
f(x)
}
Test program:
println doSomething(-1) { x -> -2*Math.asin(x) }
try { println doSomething(-1, 50) } catch (Throwable t) { println t.message }
try { println doSomething(-1, null) } catch (Throwable t) { println t.message }
Output:
3.141592653589793 f was not a closure! f: 50. Expression: (f instanceof groovy.lang.Closure). Values: f = 50 f was null!. Expression: (f != null). Values: f = null
[edit] Haskell
import Control.Exception
main = let a = someValue in
assert (a == 42) -- throws AssertionFailed when a is not 42
somethingElse -- what to return when a is 42
[edit] Java
public static void main(String[] args){
int a;
//...input or change a here
assert a == 42;//throws an AssertionError when a is not 42
assert a == 42 : "Error message"; //throws an AssertionError
//when a is not 42 with "Error message" for the message
//the error message can be any non-void expression
}
Note: assertion checking is disabled by default when you run your program with the java command. You must provide the -ea (short for -enableassertions) flag in order to enable them.
[edit] J
assert n = 42
[edit] Lisaac
? { n = 42 };
[edit] Lua
a = 5
assert (a == 42)
assert (a == 42,'\''..a..'\' is not the answer to life, the universe, and everything')
[edit] Metafont
Metafont has no really an assert built in, but it can easily created:
def assert(expr t) = if not (t): errmessage("assertion failed") fi enddef;
This assert macro uses the errmessage built in to show the "error". The
errmessage gives the error message and asks the user what to do.
Usage example:
n := 41;
assert(n=42);
message "ok";
Output (failed assertion):
This is METAFONT, Version 2.71828 (Web2C 7.5.5)
(./assert.mf
! assertion failed.
<to be read again>
;
l.4 assert(n=42);
?
[edit] Modula-3
ASSERT is a pragma, that creates a run-time error if it returns FALSE.
<*ASSERT a = 42*>
Assertions can be ignored in the compiler by using the -a switch.
[edit] Objective-C
For use within an Objective-C method:
NSAssert(a == 42, @"Error message");
If you want to use formatting arguments, you need to use the assertion macro corresponding to your number of formatting arguments:
NSAssert1(a == 42, @"a is not 42, a is actually %d", a); # has 1 formatting arg, so use NSAssert"1"
Within a regular C function you should use NSCAssert or NSCAssertN instead.
[edit] OCaml
let a = get_some_value () in
assert (a = 42); (* throws Assert_failure when a is not 42 *)
(* evaluate stuff to return here when a is 42 *)
[edit] Oz
Oz does not have an assert statement. But if different values are assigned to the same dataflow variable, an exception will be thrown (similar to Erlang).
declare
proc {PrintNumber N}
N=42 %% assert
{Show N}
end
in
{PrintNumber 42} %% ok
{PrintNumber 11} %% throws
Output:
%***************************** failure ************************** %** %** Tell: 11 = 42 %** %** Call Stack: %** procedure 'PrintNumber' in file "Oz<8>", line 3, column 0, PC = 18600220 %**--------------------------------------------------------------
[edit] Perl
While not exactly an assertion, a common Perl idiom is to use ... or die ... to throw an exception when a certain statement is false.
open FH, ">file" or die "Cannot open file: $!\n"; # $! contains the error message from the last error
my $a = 5;
#...input or change $a here
$a == 42 or die "Error message\n";
Some third-party modules might provide more detailed assertion ability.
[edit] PHP
<?php
$a = 5
#...input or change $a here
assert($a == 42) # when $a is not 42, take appropriate actions,
# which is set by assert_options()
?>
[edit] PicoLisp
There is no 'assert' keyword in PicoLisp. Common practice is either to break into an error handler:
(let N 41
(unless (= N 42) (quit "Incorrect N" N)) ) # 'quit' throws an error
41 -- Incorrect N
?
or to stop at a debug break point, allowing to continue with the program:
(let N 41
(unless (= N 42) (! setq N 42)) ) # '!' is a breakpoint
(setq N 42) # Automatically fix the value
! # Hit ENTER to leave the breakpoint
-> 42
[edit] Prolog
Works with: SWI Prolog
test(A):-
assertion(A==42).
[edit] Python
a = 5
#...input or change a here
assert a == 42 # throws an AssertionError when a is not 42
assert a == 42, "Error message" # throws an AssertionError
# when a is not 42 with "Error message" for the message
# the error message can be any expression
[edit] R
stopifnot(a==42)
[edit] Ruby
Library: test/unit.rb
require "test/unit/assertions"
include Test::Unit
include Test::Unit::Assertions
n = 5
begin
assert_equal(42, n)
rescue AssertionFailedError
puts "assertion failed: expected 42, got #{n}"
end
[edit] Scala
These two are the same thing, and are tagged @elidable(ASSERTION):
assert(a == 42)
assert(a == 42, "a isn't equal to 42")
assume(a == 42)
assume(a == 42, "a isn't equal to 42")
The next one does the same thing as above, but it is not tagged. Often used as a pre-condition checker on class constructors.
require(a == 42)
require(a == 42, "a isn't equal to 42")
This one checks a value and returns it for further use (here shown being printed). It
uses assert, which, as explained, gets tagged.
println(a.ensuring(a == 42))
println(a.ensuring(a == 42, "a isn't equal to 42"))
println(a.ensuring(_ == 42))
println(a.ensuring(_ == 42, "a isn't equal to 42"))
[edit] Scheme
Works with: Scheme version R6RS
Translation of: Common Lisp
(let ((x 42))
(assert (and (integer? x) (= x 42))))
[edit] Slate
load: 'src/lib/assert.slate'.
define: #n -> 7.
assert: n = 42 &description: 'That is not the Answer.'.
raises an AssertionFailed condition (an Error).
[edit] Tcl
Library: tcllib
package require control
set x 5
control::assert {$x == 42}
Produces the output:
assertion failed: $x == 42
[edit] VBScript
[edit] Definition
sub Assert( boolExpr, strOnFail )
if not boolExpr then
Err.Raise vbObjectError + 99999, , strOnFail
end if
end sub
[edit] Invocation
dim i
i = 43
Assert i=42, "There's got to be more to life than this!"
[edit] Output
>cscript "C:\foo\assert.vbs"
C:\foo\assert.vbs(3, 3) (null): There's got to be more to life than this!







