Strict Beyond Reproach

Pascal Cuoq made an interesting comment on my last post about C developers accidentally writing “==” in OCaml when they meant to use “=”. It reminds me of a similar issue I run into, when I am writing in OCaml but thinking in Haskell, and I am confronted with a value of type:

   'a option list


My first thought when processing this is to use the function:

    cat_options (l: 'a option list): 'a list

which behaves just like Data.Maybe.catMaybes in Haskell. But I often find myself writing things like:

   List.hd (cat_options someList)

…which would be efficient in Haskell, because catMaybes is lazy, and would only process the list until it found a value. But in OCaml, the entire list is processed by cat_options, then the first item is returned. This is wasteful, and could become a noticeable problem for long enough lists.

An efficient function would be:

let first_some (l : 'a option list) : 'a option =
  let rec aux xs =
    match xs with
    | []           -> None
    | None   :: xs -> aux xs
    | Some x :: xs -> Some x
  in
  aux l

Thanks for the kind wishes Pascal!

Tags:
No Comments

Post a Comment