Guest User

Untitled

a guest
Sep 10th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.89 KB | None | 0 0
  1. signature HASHABLE =
  2. sig
  3.   type t
  4.   val hash : t -> int
  5. end
  6.  
  7. signature HASH_TABLE =
  8. sig
  9.   structure Key : HASHABLE
  10.  
  11.   type 'v table = (Key.t * 'v) list ref (* for default's sake *)
  12.  
  13.   val newTable : unit -> 'v table
  14.  
  15.   val insert : 'v table -> Key.t -> 'v -> unit
  16.   val apply : 'v table -> (Key.t * 'v -> unit) -> unit
  17. end
  18.  
  19. structure Key1 =
  20. struct
  21.   type t = int
  22.   val hash = fn x => x
  23. end
  24.  
  25. structure Key2 =
  26. struct
  27.   type t = int
  28.   val hash = fn x => x div 2 (* the only change *)
  29. end
  30.  
  31. structure H1 : HASH_TABLE =
  32. struct
  33.  
  34.   structure Key = Key1
  35.  
  36.   type 'v table = (Key.t * 'v) list ref
  37.  
  38.   fun newTable () = ref []
  39.  
  40.   fun insert t k v =
  41.     if List.exists (fn (x,y) => (Key.hash x) = (Key.hash k)) (!t)
  42.     then t := (map (fn (x,y) =>
  43.                     if (Key.hash x) = (Key.hash k) then (x,v) else (x,y)) (!t))
  44.     else t := ((k,v) :: (!t))
  45.  
  46.   fun apply ht f = List.app f (! ht)
  47.  
  48. end
  49.  
  50. structure H2 : HASH_TABLE =
  51. struct
  52.  
  53.   structure Key = Key2
  54.  
  55.   type 'v table = (Key.t * 'v) list ref
  56.  
  57.   fun newTable () = ref []
  58.  
  59.   fun insert t k v =
  60.     if List.exists (fn (x,y) => (Key.hash x) = (Key.hash k)) (!t)
  61.     then t := (map (fn (x,y) =>
  62.                     if (Key.hash x) = (Key.hash k) then (x,v) else (x,y)) (!t))
  63.     else t := ((k,v) :: (!t))
  64.  
  65.   fun apply ht f = List.app f (! ht)
  66.  
  67. end
  68.  
  69. functor MainFn (A : sig
  70.                     structure HT1 : HASH_TABLE where type Key.t = int
  71.                     structure HT2 : HASH_TABLE where type Key.t = int
  72.                   end) =
  73. struct
  74.   open A
  75.  
  76.   fun foo () =
  77.   let
  78.     val newt = HT1.newTable ()
  79.     val () = HT1.insert newt 3 "hi"
  80.     val () = HT2.insert newt 3 "ho"
  81.     val () =
  82.       H1.apply newt (fn (k,v) => print ((Int.toString k) ^ " |-> " ^ v ^ "\n"))
  83.   in
  84.     newt (* only contains (3, "ho") ! *)
  85.   end
  86.  
  87. end
  88.  
  89. structure Main = MainFn (struct structure HT1 = H1 structure HT2 = H2 end)
Add Comment
Please, Sign In to add comment