Advertisement
unknown31415

ocaml

Aug 18th, 2022 (edited)
1,420
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Op = struct
  2.   type t =
  3.     | Plus
  4.     | Minus
  5.     | Mult
  6.     | Div
  7.   [@@deriving enumerate]
  8. end
  9. ;;
  10.  
  11. type node =
  12.   { left : expression
  13.   ; right : expression
  14.   ; op : Op.t
  15.   ; is_bracketed : bool
  16.   }
  17. and expression =
  18.   | Node of node
  19.   | Leaf of int
  20. ;;
  21.  
  22. (* enum functions to generate all possible expression of depth i *)
  23. let rec enum i =
  24.   if i = 0 then [(Leaf 0)]
  25.   else (
  26.     let possible_children = enum (i - 1) in
  27.     List.bind possible_children ~f:(fun left ->
  28.       List.bind possible_children ~f:(fun right ->
  29.         List.bind Op.all ~f:(fun op ->
  30.           List.bind Bool.all ~f:(fun is_bracketed ->
  31.           [Node { left; right; op; is_bracketed }])))))
  32. ;;
  33.  
  34. (* to_str functions *)
  35. let op_to_str = function
  36.   | Op.Plus -> "+"
  37.   | Minus -> "-"
  38.   | Mult -> "*"
  39.   | Div -> "/"
  40. ;;
  41.  
  42. let rec expression_to_str = function
  43.   | Leaf x -> Int.to_string x
  44.   | Node { left; right; op; is_bracketed } ->
  45.     let inside = (expression_to_str left) ^ (op_to_str op) ^ (expression_to_str right) in
  46.     if is_bracketed then
  47.       "(" ^ inside ^ ")"
  48.     else inside
  49. ;;
  50.  
  51. (* finally running *)
  52. utop # enum 2 |> List.map ~f:expression_to_str;;
  53. - : string list =
  54. ["0+0+0+0"; "(0+0+0+0)"; "0+0-0+0"; "(0+0-0+0)"; "0+0*0+0"; "(0+0*0+0)";
  55.  "0+0/0+0"; "(0+0/0+0)"; "0+0+(0+0)"; "(0+0+(0+0))"; "0+0-(0+0)";
  56.  "(0+0-(0+0))"; "0+0*(0+0)"; "(0+0*(0+0))"; "0+0/(0+0)"; "(0+0/(0+0))";
  57.  "0+0+0-0"; "(0+0+0-0)"; "0+0-0-0"; "(0+0-0-0)"; "0+0*0-0"; "(0+0*0-0)";
  58.  "0+0/0-0"; "(0+0/0-0)"; "0+0+(0-0)"; "(0+0+(0-0))"; "0+0-(0-0)";
  59.  "(0+0-(0-0))"; "0+0*(0-0)"; "(0+0*(0-0))"; "0+0/(0-0)"; "(0+0/(0-0))";
  60.  "0+0+0*0"; "(0+0+0*0)"; "0+0-0*0"; "(0+0-0*0)"; "0+0*0*0"; "(0+0*0*0)";
  61.  "0+0/0*0"; "(0+0/0*0)"; "0+0+(0*0)"; "(0+0+(0*0))"; "0+0-(0*0)"; ...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement