open StateMonad
type 'a tree = | Leaf of 'a
| Node of 'a tree * 'a tree
// F# Monadic tree labeller
let rec private mNode x =
match x with
| Leaf(c) -> state { let! x = GetState
do! SetState (x + 1)
return Leaf(c,x) }
| Node(l,r) -> state { let! l = mNode(l)
let! r = mNode(r)
return Node(l,r) }
let mLabel x = Execute(mNode(x))
// F# Non-Monadic manual state passing tree labeller
let Label a s =
let rec Lab' a s =
match a with
|Leaf(c) -> (Leaf(c,s), s + 1)
|Node(l,r) -> let l' = Lab' l s
let r' = Lab' r (snd l')
(Node(fst l', fst r'), (snd r'))
fst (Lab' a s)
Useful snippets of F# code, formatted in a way that makes it easy to copy and paste the snippet in the F# Interactive editor.
Saturday 13 December 2008
F# Monadic tree labeller
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment