0 people like it.

Generating a tree from a generic type

I needed a function to generate a tree from a c# class that had some odd semantics, but when I refactored it, I realised almost everyone must have something similar knocking around their codebase, so here's mine.

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
type Tree<'T> =
        |Branch of 'T * seq<Tree<'T>>
        |Leaf of 'T

let rec GenerateTreeFromRecursiveObject hasChildren generateChildren current =
    let generateTree = GenerateTreeFromRecursiveObject hasChildren generateChildren
    match hasChildren current with
    | true -> Branch(current, seq{for next in generateChildren current do yield (generateTree next)})
    | false -> Leaf(current)
union case Tree.Branch: 'T * seq<Tree<'T>> -> Tree<'T>
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
type Tree<'T> =
  | Branch of 'T * seq<Tree<'T>>
  | Leaf of 'T

Full name: Script.Tree<_>
union case Tree.Leaf: 'T -> Tree<'T>
val GenerateTreeFromRecursiveObject : hasChildren:('a -> bool) -> generateChildren:('a -> #seq<'a>) -> current:'a -> Tree<'a>

Full name: Script.GenerateTreeFromRecursiveObject
val hasChildren : ('a -> bool)
val generateChildren : ('a -> #seq<'a>)
val current : 'a
val generateTree : ('a -> Tree<'a>)
val next : 'a
Raw view Test code New version

More information

Link:http://fssnip.net/k0
Posted:11 years ago
Author:Sean Newham
Tags: recursion , sequences , yield