Saturday, 13 December 2008

F# Monadically label n-ary tree

// F# Monadically label n-ary tree
let MMap f xs =
let rec MMap' (f, xs', out) =
state {
match xs' with
| h :: t -> let! h' = f(h)
return! MMap'(f, t, List.append out [h'])
| [] -> return out
}
MMap' (f, xs, [])

type 'a ntree = | NLeaf of 'a
| NNode of 'a ntree list


let rec private MNNode (x) =
match x with
| NLeaf(c) -> state { let! x = GetState
do! SetState (x + 1)
return NLeaf(c,x) }

| NNode(xs) -> state { let! xs' = MMap MNNode xs
return NNode(xs') }

let MNLabel x = Execute(MNNode(x))

No comments: