Reputation: 195
To handle exceptional cases in OCaml, it is often possible to choose to either catch exceptions or to use the type 'a option
. If I understand correctly, both choices are possible for Streams thanks to the functions Stream.next
(raises an exception) and Stream.peek
/Stream.junk
(return 'a option
).
Is there any difference between
match Stream.peek t with
| None -> ***
| Some c -> Stream.junk t; *****
and
try
let c = Stream.next t in *****
with Stream.Failure -> ***
where t
is a variable of type 'a stream
and ***
and *****
are some sequences of expressions?
Edit 2020-12-03
Since OCaml 4.02, it is also possible to write the above as
match Stream.next t with
| c -> *****
| exception Stream.Failure -> ***
which may be preferable if further pattern matching is to be done on c
, e.g.,
match Stream.next t with
| [] -> *****
| a::b -> *******
| exception Stream.Failure -> ***
(source: Xavier Leroy's slides What's new in OCaml 4.02).
Upvotes: 1
Views: 339
Reputation: 66823
There is no difference in behavior, as you note.
The version with an option type will cons up some more data, as it has to create Some x
for each value returned. This will be a minor effect in general because OCaml is excellent at garbage collecting short-lived values.
I personally like using options because of the parallelism between the two cases. But using peek
and junk
seems quite a bit clunkier than just having a function that returns an option. So for this case I might use the exception-based handling.
In other words, it's a judgement call (in my opinion).
Upvotes: 2