3 people like it.

Converting binary tree to sequence using yield

This sample show how to use seq-yield syntax to convert a binary tree to a sequence of elements.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
type 't btree = 
  | Nil
  | Node of 't * 't btree * 't btree

let Leaf x = Node(x,Nil,Nil)

let x = Node(0,Node(1,Leaf(2),Nil),Node(3,Leaf(4),Leaf(5)))

let rec ToSeq t = seq {
    match t with
    | Nil -> ()
    | Node(x,L,R) ->
        yield! ToSeq L
        yield x
        yield! ToSeq R
}

x |> ToSeq
union case btree.Nil: 't btree
union case btree.Node: 't * 't btree * 't btree -> 't btree
type 't btree =
  | Nil
  | Node of 't * 't btree * 't btree

Full name: Script.btree<_>
val Leaf : x:'a -> 'a btree

Full name: Script.Leaf
val x : 'a
val x : int btree

Full name: Script.x
val ToSeq : t:'a btree -> seq<'a>

Full name: Script.ToSeq
val t : 'a btree
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<_>
val L : 'a btree
val R : 'a btree
Raw view Test code New version

More information

Link:http://fssnip.net/7TY
Posted:7 years ago
Author:Dmitry Soshnikov
Tags: binary tree , seq , yield