I am trying to represent a tree data-structure in F# using the following type:
type Node =
val mutable left: Node option
val mutable right: Node option
val mutable value: int
new (l, r, v) = {left = l; right = r; value = v}
I can create a tree like this:
let root = new Node (Some (new Node (None, None, 2)), Some (new Node (None, None, 3)), 1)
I now want to traverse using pattern matching. However, i dont know how to pattern match objects. I tried something like this:
let rec traverse r =
match r with
| Node (None, None, v) -> printfn "%d" v
and stopped right there because the pattern-matching is wrong.
EDIT: After Petricek's answer, I did not use all his suggestions because I haven't read about discriminated unions and other class features yet. I will implement once i know more about these things. But for time-being, this is how it looks:
type Node =
val left: Node option
val right: Node option
val value: int
new (l, r, v) = {left = l; right = r; value = v}
let (|Node|) (nd: Node) = (nd.left, nd.right, nd.value)
let root = new Node (Some (new Node (None, None, 2)), Some (new Node (None, None, 3)), 1)
let rec traverseLRtR r =
match r with
| Node (None, None, v) -> printfn "%d" v
| Node (left, right, v) -> traverseLRtR left.Value; traverseLRtR right.Value; printfn "%d" v;
traverseLRtR root
Output is:
2
3
1