f# - Casting discriminated union without common ancestor -
i have discriminated union:
type attribute = | of o : | b of o : b | none i have function wich return list of attributes (attribute list).
let attributes = foo i need create function gets list of attributes , return result type where:
type result = { : a[] b : b[] } th function must each element of list , add corresponding array of result type.
here attempt:
let justdoit (attributes : attribute list) : result = let result = { = array.empty; b = array.empty } let accumulate (a : attribute) (accum : result) : result = match | o -> o :?> |> array.append accum.a accum let rec foo (attributes : attribute list) (accum : result) : result = match attributes | [] -> accum | hd::tail -> foo tail (accumulate hd accum) foo attributes result i have problem in accumulate function when tying cast discriminated union specific type.
is there way or beter solve task different approach ?
updated:
type = { : int } type b = { : string }
you can use seq.fold (rather writing recursive processing yourself). looks nicer if store results lists, because can append new elements using :: operator:
let justdoit attributes = attributes |> seq.fold (fun ({ = alist; b = blist } st) -> match | a -> { st = :: alist } | b b -> { st b = b :: blist } | _ -> st ) { = []; b = [] }
Comments
Post a Comment