From: Brian H. <bri...@ql...> - 2003-05-30 21:33:53
|
Count is called, generally, for two reasons: 1) To pre-reserve space for all the elements in the enumeration. This is how dynArray uses it. 2) To see if there are any more elements left in the enumeration (count > 0). The second case is the interesting one- it can always be O(1). And it's the information we most often need. So why not provide it directly? Iter and map then start looking like: let iter f t = let rec loop () = if t.has_next() then f (t.next()); loop () else () in loop () let fold f init t = let rec loop accu = if t.has_next() then loop (f (t.next()) accu) else accu in loop init In extString, we'd have: let enum l = let lr = ref l in Enum.make ~next:(fun () -> match !lr with | [] -> raise Enum.No_more_elements | h :: t -> lr := t; h ) ~count:(fun () -> length !lr ) ~has_next:(fun () -> match !lr with | [] -> false | _ -> true ) This gets rid of the annoying O(N) count cost. Brian |