Programmation Fonctionnelle, TP3

Version & licenses
Creative Commons License

Programmation Fonctionnelle, TP3 : trie.ml

Guyslain Naves
  1. module Make = functor (K : Set.OrderedType) ->
  2. struct

  3. type key = K.t
  4. module M = Map.Make(K)

  5. type 'a t =
  6. { value : 'a option;
  7. sons : ('a t) M.t
  8. }

  9. let empty = { value = None; sons = M.empty }

  10. let rec add key_lst value trie =
  11. match key_lst with
  12. | [] -> { trie with value = Some value }
  13. | key::key_lst ->
  14. let sub_trie =
  15. if M.mem key trie.sons then M.find key trie.sons
  16. else empty
  17. in
  18. { trie with sons = M.add key (add key_lst value sub_trie) trie.sons }

  19. let rec mem key_lst trie =
  20. match key_lst with
  21. | [] -> trie.value <> None
  22. | key::key_lst -> M.mem key trie.sons && (mem key_lst (M.find key trie.sons))

  23. let rec find key_lst trie =
  24. match key_lst, trie.value with
  25. | [], Some value -> value
  26. | [], None -> failwith "Not found"
  27. | key::key_lst, _ ->
  28. if M.mem key trie.sons then find key_lst (M.find key trie.sons)
  29. else failwith "Not found"


  30. let rec longest stream trie =
  31. if Stream_lzw.is_empty stream then
  32. if trie.value = None then None else Some ([],stream)
  33. else
  34. let (key,str) = Stream_lzw.read stream in
  35. let longest_tail =
  36. if M.mem key trie.sons then longest str (M.find key trie.sons)
  37. else None
  38. in
  39. match longest_tail, trie.value with
  40. | Some (l1,stream), _ -> Some (key::l1,stream)
  41. | None, None -> None
  42. | None, Some _ -> Some ([],stream)


  43. let rec fold f trie init =
  44. let updated_value =
  45. match trie.value with
  46. | Some value -> f [] value init
  47. | None -> init
  48. in
  49. M.fold
  50. (fun key trie value -> fold (fun kl b v -> f (key::kl) b v) trie value)
  51. trie.sons
  52. updated_value

  53. end