insert - F# Tree: Node Insertion -


this question extends f# recursive tree validation, had nicely answered yesterday.

this question concerns inserting child in existing tree. updated type i'd use:

type name           = string type birthyear      = int type familytree     = person of name * birthyear * children , children        = familytree list 

my last question concerned checking validity of tree, solution decided go with:

let rec checkages minbirth = function     | person(_,b,_) :: t -> b >= minbirth && checkages b t     | [] -> true  let rec validate (person(_,b,c)) =     list.forall iswf c && checkages (b + 16) c 

now able insert person simon child of specific person hans in following form

insertchildof "hans" simon:person casperfamily:familytree;; 

so, input should parent name, child , family tree. ideally should return modified family tree, familytree option

what struggling incorporating validate function make sure legal, , way insert in list of children, if insertion person parent - maybe seperate function.

all welcome , appreciated - thanks! :)

after comment here's code behave expected:

let insert pntname (person(_, newprsnyear, _) newprsn) (person (n,y,ch)) =     let rec ins n y = function         | [] -> if y < newprsnyear && n = pntname [newprsn] else none         | (person (name, year, childs) person) :: bros ->             let trynxtbros() = option.map (fun x -> person::x) (ins n y bros)             if y < newprsnyear && n = pntname // father ok                 if newprsnyear < year // brother ok -> insert here                     (newprsn::person::bros)                 else trynxtbros()             else // keep looking, first eldest child ...                 match ins name year childs                 | -> (person (name, year, i) :: bros)                 | _      -> trynxtbros() // ... other childs     option.map (fun x -> person (n, y, x)) (ins n y ch) 

as in previous answer keep avoiding using list functions since don't think fit in tree structure unless tree provides traverse.

i might bit purist in sense use either list functions (with lambdas , combinators) or pure recursion, in general don't mixing them.


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -