Composite pattern with variable

Category:
Design patterns
Description: This implementation uses a global variable resultRef to hold the result. For more information, please go to http://en.wikipedia.org/wiki/Composite_pattern
Code:
type CompositeNode<'T> = 
| Node of 'T
| Tree of 'T * CompositeNode<'T> * CompositeNode<'T>
with
member this.InOrder f =
match this with
| Tree(n, left, right) ->
left.InOrder(f)
f(n)
right.InOrder(f)
| Node(n) -> f(n)
member this.PreOrder f =
match this with
| Tree(n, left, right) ->
f(n)
left.PreOrder(f)
right.PreOrder(f)
| Node(n) -> f(n)
member this.PostOrder f =
match this with
| Tree(n, left, right) ->
left.PostOrder(f)
right.PostOrder(f)
f(n)
| Node(n) -> f(n)

let OtherCompositePatternSample2() =
let tree = Tree(1, Tree(11, Node(12), Node(13)), Node(2))
let resultRef = ref 0
let nodeAccessFunc n = resultRef := !resultRef + n
tree.PreOrder nodeAccessFunc
printfn "result = %d" !resultRef

Assert.AreEqual(!resultRef, 39)

Execution Result:
result = 39
both elements are equal

Last edited Sep 14, 2011 at 3:22 AM by ttliu2000, version 1

Comments

No comments yet.