Advertisement
Guest User

Untitled

a guest
Jul 28th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.57 KB | None | 0 0
  1. #use "topfind" ;;
  2. #require "pcre" ;;
  3.  
  4. type tree = Node of string * tree list | Leaf of string
  5.  
  6. let () = Random.self_init ()
  7.  
  8. let ( |> ) x f = f x
  9.  
  10. let shuffle arr =
  11.   let len = Array.length arr in
  12.   for i = 0 to len - 2 do
  13.     let r = i + Random.int (len - i - 1) in
  14.     let x = Array.unsafe_get arr i in
  15.     let y = Array.unsafe_get arr r in
  16.     Array.unsafe_set arr i y ;
  17.     Array.unsafe_set arr r x
  18.   done
  19.  
  20. let words =
  21.   let ws = ref [] in
  22.   let ic = Pervasives.open_in "/usr/share/dict/words" in
  23.   Pcre.foreach_line ~ic (fun w -> ws := w :: !ws) ;
  24.   Pervasives.close_in ic ;
  25.   let ret = Array.of_list (List.rev !ws) in
  26.   shuffle ret ;
  27.   ret
  28.  
  29. let random_word () =
  30.   Array.length words
  31.   |> Random.int
  32.   |> Array.unsafe_get words
  33.  
  34. let rec rev_list_init n curr fn = match n with
  35.   | 0 -> fn 0 :: curr
  36.   | _ -> rev_list_init (n - 1) (fn n :: curr) fn
  37.  
  38. let list_init n fn =
  39.   if n <= 0 then [] else rev_list_init (n - 1) [] fn
  40.  
  41. let randtree =
  42.   let rec make dep = match dep with
  43.     | 0 -> Leaf (random_word ())
  44.     | _ ->
  45.         Node (random_word (),
  46.               list_init (1 + Random.int (dep + 1)) (fun _ -> make (dep - 1)))
  47.   in
  48.   make 4
  49.  
  50. let rec p_tree ff = function
  51.   | Leaf lf -> Format.pp_print_string ff lf
  52.   | Node (nd, kids) ->
  53.       Format.fprintf ff "@[<v2>%s@,%a@]"
  54.         nd p_trees kids
  55.  
  56. and p_trees ff = function
  57.   | [ ] -> ()
  58.   | [tr] ->
  59.       p_tree ff tr
  60.   | tr :: trs ->
  61.       p_tree ff tr ;
  62.       Format.pp_print_cut ff () ;
  63.       p_trees ff trs
  64.  
  65. let () =
  66.   Format.eprintf "Here's a random tree@.%a@." p_tree randtree
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement