From: Janne H. <jjh...@gm...> - 2008-04-22 19:18:15
|
Looks good, I would find this useful. Janne On Tue, Apr 22, 2008 at 3:45 AM, Richard Jones <ri...@an...> 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: > > <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 > > ------------------------------------------------------------------------- > 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. > > http://ad.doubleclick.net/clk;198757673;13503038;p?http://java.sun.com/javaone > _______________________________________________ > ocaml-lib-devel mailing list > oca...@li... > https://lists.sourceforge.net/lists/listinfo/ocaml-lib-devel > |