Sha256: f55d3511090e45b895b4ec2660c15d20b4b59c1fd9cadf9e191dfe4586149fdc

Contents?: true

Size: 945 Bytes

Versions: 256

Compression:

Stored size: 945 Bytes

Contents

module BinarySearchTree

type Node = { left: Node option; value: int; right: Node option }

let left node  = node.left
let right node = node.right
let value node = Some node.value

let singleton value = { left = None; right = None; value = value }

let rec insert newValue (tree: Node) =
    let loop newValue = 
        function
        | Some x -> Some <| insert newValue x
        | None   -> Some <| singleton newValue

    match newValue with
    | x when x <= tree.value -> 
        { tree with left  = loop newValue tree.left }
    | _ -> 
        { tree with right = loop newValue tree.right }

let toList tree = 
    let rec loop = 
        function
        | Some node -> loop node.left @ [node.value] @ loop node.right
        | None -> []

    loop <| Some tree

let fromList = 
    function
    | []    -> failwith "Cannot create tree from empty list."
    | x::xs -> List.fold (fun acc elem -> insert elem acc) (singleton x) xs

Version data entries

256 entries across 256 versions & 1 rubygems

Version Path
trackler-2.2.1.105 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.104 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.103 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.102 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.101 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.100 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.99 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.98 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.97 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.96 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.95 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.94 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.93 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.92 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.91 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.90 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.89 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.88 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.87 tracks/fsharp/exercises/binary-search-tree/Example.fs
trackler-2.2.1.86 tracks/fsharp/exercises/binary-search-tree/Example.fs