Advertisement
Guest User

Untitled

a guest
Jan 19th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.33 KB | None | 0 0
  1. type Tree =
  2.     | Empty
  3.     | Node of value:char * weight:int * left:Tree * right:Tree
  4.  
  5. let countOccurrances str =
  6.     str|>Seq.countBy id
  7.  
  8. let createLeaves occ =
  9.     occ|> Seq.map (fun (c,w) -> Node(c, w, Empty, Empty))
  10.  
  11. let sortByWeight t =
  12.         match t with
  13.         |Node(_,w,_,_) -> w
  14.         |Empty -> failwith "Empty Nodes"
  15.  
  16. let rec buildTree leaves =
  17.     match Seq.length leaves with
  18.     |1 -> Seq.head leaves
  19.     |_ ->
  20.         let nodes = leaves |> Seq.sortBy sortByWeight
  21.         let left = Seq.item 1 nodes
  22.         let right = Seq.head nodes
  23.         match (left, right) with
  24.         |(Node(_,w1,_,_), Node(_,w2,_,_)) -> Seq.skip 2 nodes |> Seq.append [Node('\n', w1+w2, left, right)] |> buildTree
  25.         |_ -> failwith "Empty Nodes"
  26.  
  27. let rec printTree bitString root =
  28.     match root with
  29.     |Node(v,_,l,r) ->
  30.         match (l,r) with
  31.         |(Node(_,_,_,_), Node(_,_,_,_)) ->
  32.             printTree (Seq.append bitString [1]) l
  33.             printTree (Seq.append bitString [0]) r
  34.         |_ ->
  35.             let str =
  36.                 match Seq.length bitString with
  37.                 |0 -> Seq.init 1 (fun i -> i)
  38.                 |_ -> bitString
  39.             printfn "%A : %c" str v
  40.     |_ -> failwith "Root is Empty"
  41.  
  42. "aaaaaaaabbbbccd" |> countOccurrances |> createLeaves |> buildTree |> printTree Seq.empty
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement