I found this type zipper
and get
functions defined like this:
type 'a zipper = 'a list * int
exception Empty
let empty = ([], 0)
(* get: returns the sublist starting at focus position *)
let rec get lz =
match lz with
| (l, 0) -> l
| (h::t, n) when n > 0 -> get (t, n-1)
| _ -> raise Empty
But that when n > 0
is not clear to me, that is not necessary, because assuming we will provide argument n > 0
, it will always be captured by the first match, isn't this correct? Why that when n > 0
?
But you can't assume that the value of n
will either be 0
or a positive value, because int
is a signed type.
Nothing would stop you some writing:
get ([1;2;3;4;5;6], -1)
Though Empty
is a very odd choice of names for an exception in this situation. It would make much more sense to use either Not_found
or even better, Invalid_argument
.
I would further add that the type alias here seems rather non-idiomatic. Rather:
let rec get i lst =
match lst, i with
| l, 0 -> l
| h::t, n when n > 0 -> get (i-1) t
| _ -> invalid_arg "Negative index"