I was actually thinking about something very similar to this earlier and it actually becomes very elegant using sequence expressions, heres an example which may be useful:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#light
#nowarn "57"

type 'a tree =
    Node of 'a * 'a tree list

let tree_elements max_depth tree =
    let rec aux depth (Node(value, children)) =
        if depth < max_depth then
            seq { yield value
                  for child in children ->>
                      aux (depth + 1) child }
        else
            Seq.empty

    aux 0 tree

do
    let tree = Node(1, [ Node(2, [Node(3, [])])
                       ; Node(4, [Node(5, [])])])
    
    for depth = 1 to 3 do
        Printf.printf "depth = %d\n" depth
        for elem in tree_elements depth tree do
            Printf.printf "%d " elem
        print_newline()
    read_line() |> ignore
By on 10/29/2007 6:16 AM ()

You might also like to look at my code for binary trees here.

By on 10/29/2007 6:08 AM ()

The classique way to create and work with trees in F# is using sum type and pattern matching.

Here's a sample taken from foundations of F#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 #light

// tree type
type Tree<'a> =
| Node of Tree<'a> list
| Value of 'a

// creating the tree
let tree =
    Node( [ Node( [Value "one"; Value "two"] ) ;
        Node( [Value "three"; Value "four"] ) ] )


// walking the tree
let rec printTreeValues x =
    match x with
    | Node l -> List.iter printTreeValues l
    | Value x ->
        print_any x
        print_string ", "
        
// apply the tree function
printTreeValues tree

If you want to create a collection nodes, then you'd probably add accumalator parameter to the tree walking function. I know this doesn't exactly answer question, but hope it helps a bit. If you eleborate a bit more about what your trying to do with the tree I might be able to help a bit more.

Cheers,
Rob

By on 10/28/2007 6:46 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper