Filtering OCaml list to one variant -
so have list of stmt
(algebraic type) contain number of vardecl
within list. i'd reduce list stmt list
vardecl list
. when use list.filter
can eliminate other types i'm still left stmt list
.
i found able filtering type change folding, can't figure out how generalize (i need pattern many places in project).
let decls = list.fold_left (fun lst st -> match st | vardecl(vd) -> vd :: lst | _ -> lst ) [] stmts in
is there better way perform filter , cast variant of list type?
assuming have type like
type stmt = vardecl of int | foo of int | bar | fie of string
and stmt list, batteries lets do
let vardecl_ints l = list.filter_map (function vardecl -> | _ -> none) l let foo_ints l = list.filter_map (function foo -> | _ -> none) l
which think concise you're going get. don't think can make general "list-getters" adt's, because e.g.
let bars l = list.filter_map (function bar -> bar | _ -> none) l
https://github.com/ocaml-batteries-team/batteries-included/blob/master/src/batlist.mlv#l456 has batteries implementation of filter_map, if don't want dependency. functional version [] instead of acc quite similar, doing (x::dst) , |>list.rev
@ end.
Comments
Post a Comment