Advertisement
Guest User

ocaml

a guest
Aug 17th, 2022
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.40 KB | None | 0 0
  1. type pure =
  2.     | Binary of expression * Ops.t * expression
  3.     | Atom of int
  4.     and bracketed = pure
  5.     and expression =
  6.     | Bracketed of bracketed
  7.     | Pure of pure
  8. ;;
  9.  
  10. type pure = Binary of expression * Ops.t * expression | Atom of int
  11. and bracketed = pure
  12. and expression = Bracketed of bracketed | Pure of pure
  13.  
  14. let rec enum' i =
  15. if i = 0 then [(Atom 0)]
  16. else (
  17.   let children = enum (i - 1) in
  18.   List.cartesian_product children children |> List.map ~f:(fun (child1, child2) ->
  19.     List.concat_map Ops.all ~f:(fun op ->
  20.       [(Binary (child1, op, child2))]
  21. ))) |> List.concat
  22. and enum i = let children = enum' i in
  23. [List.map children ~f:(fun child -> Pure(child));
  24. List.map children ~f:(fun child -> Bracketed(child))
  25. ] |> List.concat
  26. ;;
  27. let ops_to_str = function
  28. | Ops.Plus -> "+"
  29. | Minus -> "-"
  30. | Mult -> "*"
  31. | Div -> "/"
  32. ;;
  33. let rec pure_to_str = function
  34. | Binary (e1, op, e2) -> (expr_to_str e1) ^ (ops_to_str op) ^ (expr_to_str e2)
  35. | Atom x -> Int.to_string x
  36. and bracket_to_str e = "(" ^ (pure_to_str e) ^ ")"
  37. and expr_to_str = function
  38. | Bracketed x-> bracket_to_str x
  39. | Pure x -> pure_to_str x
  40. ;;
  41. enum 2 |> List.map ~f:expr_to_str;;
  42. - : string list =
  43. ["0+0+0+0"; "0+0-0+0"; "0+0*0+0"; "0+0/0+0"; "0+0+0-0"; "0+0-0-0"; "0+0*0-0";
  44.  "0+0/0-0"; "0+0+0*0"; "0+0-0*0"; "0+0*0*0"; "0+0/0*0"; "0+0+0/0"; "0+0-0/0";
  45.  "0+0*0/0"; "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