Advertisement
Guest User

Untitled

a guest
May 15th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.96 KB | None | 0 0
  1. open System
  2. type Heap<'a when 'a: equality> =
  3. | EmptyHP
  4. | HP of 'a * Heap<'a> * Heap<'a>
  5.  
  6.  
  7. let ex3 = HP(1,HP(2,HP(3,EmptyHP,EmptyHP),HP(5,EmptyHP,EmptyHP)),HP(4,EmptyHP,EmptyHP))
  8.  
  9. // The type of ex3 is monomorphic. The reason for this is that it is Heap<int>, which means that it has to contain heap with ints.
  10. // If the type was polymorphic, the type would be Heap<'a>
  11.  
  12. let empty = EmptyHP
  13.  
  14. exception HeapError of string
  15.  
  16. //Checks if a heap is empty.
  17. let isEmpty = function
  18. | EmptyHP -> true
  19. | _ -> false
  20.  
  21. // returns the number of notes within a heap (root inclusive)
  22. let rec size = function
  23.     | EmptyHP -> 0
  24.     | HP(_,l,r) -> 1 + size l + size r
  25.  
  26. // finds the root value and raises exception if the root is empty
  27. let find = function
  28. | HP(v,_,_) -> v
  29. | EmptyHP -> raise (HeapError "empty")
  30.  
  31. // test cases
  32. let not_a_heap = HP(1,HP(4,HP(3,EmptyHP,EmptyHP),HP(5,EmptyHP,EmptyHP)),HP(4,EmptyHP,EmptyHP))
  33. let not_a_heap2 = HP(3,HP(2,HP(3,EmptyHP,EmptyHP),HP(5,EmptyHP,EmptyHP)),HP(4,EmptyHP,EmptyHP))
  34.  
  35. // this functions checks if the heap property is fulfilled. The root node should always be bigger or equal to the child notes
  36. let chkHeapProperty h =
  37.     let rec aux h =
  38.         match h with
  39.         | HP(v,l,r) -> if ((isEmpty l || v < find l) && (isEmpty r || v <find r)) then (aux l) && (aux r) else false
  40.         | EmptyHP -> true
  41.     aux h
  42.  
  43. let test_chkHeapProperty =
  44.     chkHeapProperty ex3 && not (chkHeapProperty not_a_heap && chkHeapProperty not_a_heap2)
  45.  
  46. //I made the topdown with preordering. I apply the function first, then I do left and right child node.
  47. let map f h =
  48.     let rec aux h =
  49.         match h with
  50.         | HP(v,l,r) -> HP(f v, aux l, aux r)
  51.         | EmptyHP -> EmptyHP
  52.     aux h
  53.  
  54.  
  55. // this function can easily destroy a heap property; however, to do so it must not contain only uneven numbers
  56. let destroy_heap_property h =
  57.     let new_heap = map (fun i -> if (i % 2 = 0) then i*(-1) else i) h
  58.     chkHeapProperty new_heap
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement