Tuan
Tuan

Reputation: 94

assert in one standalone ocaml program

Having read this thread , I put this code into my .ml file:

let x = [3;5;9]
(* Testing append to the list *)
let () = assert( x @ [2;10] == [3;5;9;2;10])

And run

$ ocamlc -o BasicList BasicList.ml  && ./BasicList 
Fatal error: exception Assert_failure("BasicList.ml", 3, 9)

Upvotes: 0

Views: 157

Answers (1)

Read the documentation of Ocaml.

In recent Stdlib, you probably want to use the = structural equality operator and code

 assert( x @ [2;10] = [3;5;9;2;10])

Notice that == is coding the physical equality operator (of "pointers", more precisely of physical boxed values).

val (==) : 'a -> 'a -> bool

e1 == e2 tests for physical equality of e1 and e2. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, e1 == e2 is true if and only if physical modification of e1 also affects e2. On non-mutable types, the behavior of ( == ) is implementation-dependent; however, it is guaranteed that e1 == e2 implies compare e1 e2 = 0. Left-associative operator, see Ocaml_operators for more information.

BTW, the ocaml programming language has an open source implementation. You should consider studying its source code.

Be aware that comparing with = two long lists of length n has a time complexity of O(n). But == is constant time. For lists of many thousands of elements that makes a difference.

As an exercise, code the equivalent of = for lists (e.g. using just a letrec, match and ==).

Upvotes: 2

Related Questions