In OCaml, when having to check for the emptiness of a list data structure lst
, I would like to use
if (lst = []) then ...
for its conciseness, instead of using pattern matching or checking length of the list.
I wonder if there is any side effect of this structural comparison (=)
over the list data structure?
A list is an ordered sequence of elements. All elements of a list in OCaml must be the same type. Lists are built into the language and have a special syntax. Here is a list of three integers: # [1; 2; 3];; - : int list = [1; 2; 3] Note semicolons separate the elements, not commas.
There are no side effects. It's a perfectly good way to test whether a list is empty.
Many times however, you'd like to work with some elements of the list if it's not empty. Pattern matching is good for those times.
As a tiny side comment, if you're interested in conciseness you don't need the parentheses in your if
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With