Looks good, I would find this useful.


On Tue, Apr 22, 2008 at 3:45 AM, Richard Jones <rich@annexia.org> wrote:
I'd like to propose the following function for inclusion in ExtList:

      [find_map pred list] finds the first element of [list] for which
      [pred element] returns [Some r].  It returns [r] immediately
      once found.

      @raise Not_found if no element matches the predicate.

      See also {!filter_map}.

 val find_map : ('a -> 'b option) -> 'a list -> 'b

 let rec find_map f = function
   | [] -> raise Not_found
   | x :: xs ->
       match f x with
       | Some y -> y
       | None -> find_map f xs

The HOF is analogous to filter_map, but only returns the first element
found, rather than all matching elements.

I find this HOF useful when iterating over XML [1].  For example if
you have XML like this:

   <arch name='ppc'/>

and you want to find the <os_type> content, then assuming 'guest' is a
variable containing the child nodes of <guest>:

 let os_type =
     find_map (
         | Element ("os_type", _, [PCData "hvm"]) -> Some VT_HVM
         | Element ("os_type", _, [PCData "xen"]) -> Some VT_Xen
         | _ -> None
     ) guest
     Not_found -> VT_Unknown in

If nobody objects I would like to add this to extlib.


[1] I know it'd be better to do this with CDuce, but that would
require there to be some sort of schema to the XML which doesn't
change with the phase of the moon.

Richard Jones
Red Hat

This SF.net email is sponsored by the 2008 JavaOne(SM) Conference
Don't miss this year's exciting event. There's still time to save $100.
Use priority code J8TL2D2.
ocaml-lib-devel mailing list