From: Richard J. <ri...@an...> - 2008-04-22 10:45:09
|
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: <guest> <os_type>hvm</os_type> <arch name='ppc'/> </guest> and you want to find the <os_type> content, then assuming 'guest' is a variable containing the child nodes of <guest>: let os_type = try find_map ( function | Element ("os_type", _, [PCData "hvm"]) -> Some VT_HVM | Element ("os_type", _, [PCData "xen"]) -> Some VT_Xen | _ -> None ) guest with Not_found -> VT_Unknown in If nobody objects I would like to add this to extlib. Rich. [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 |