Created
December 29, 2020 21:33
-
-
Save hamzamuric/279d49bd3999535ccbb159ca3af49a86 to your computer and use it in GitHub Desktop.
Factorize (n * x) + (n * y) to become n * (x + y) and multiply_out to do reverse.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type expr = | |
| Plus of expr * expr | |
| Minus of expr * expr | |
| Times of expr * expr | |
| Divide of expr * expr | |
| Value of string | |
let rec to_string e = | |
match e with | |
| Plus (left, right) -> | |
"(" ^ to_string left ^ " + " ^ to_string right ^ ")" | |
| Minus (left, right) -> | |
"(" ^ to_string left ^ " - " ^ to_string right ^ ")" | |
| Times (left, right) -> | |
"(" ^ to_string left ^ " * " ^ to_string right ^ ")" | |
| Divide (left, right) -> | |
"(" ^ to_string left ^ " / " ^ to_string right ^ ")" | |
| Value v -> v;; | |
let rec multiply_out e = | |
match e with | |
| Times (e1, Plus (e2, e3)) -> | |
Plus (Times (multiply_out e1, multiply_out e2), | |
Times (multiply_out e1, multiply_out e3)) | |
| Times (Plus (e1, e2), e3) -> | |
Plus (Times (multiply_out e1, multiply_out e3), | |
Times (multiply_out e2, multiply_out e3)) | |
| Plus (left, right) -> | |
Plus (multiply_out left, multiply_out right) | |
| Minus (left, right) -> | |
Minus (multiply_out left, multiply_out right) | |
| Times (left, right) -> | |
Times (multiply_out left, multiply_out right) | |
| Divide (left, right) -> | |
Divide (multiply_out left, multiply_out right) | |
| Value v -> Value v;; | |
let factorize e = | |
match e with | |
| Plus (Times (e1, e2), Times (e3, e4)) when e1 = e3 -> | |
Times (e1, Plus (e2, e4)) | |
| Plus (Times (e1, e2), Times (e3, e4)) when e2 = e4 -> | |
Times (Plus (e1, e3), e4) | |
| e -> e;; | |
let print_expr e = | |
print_endline (to_string e);; | |
print_expr (Times (Value "n", Plus (Value "x", Value "y")));; | |
print_expr (multiply_out (Times (Value "n", Plus (Value "x", Value "y"))));; | |
print_expr (factorize (Plus (Times (Value "n", Value "x"), Times (Value "n", Value "y"))));; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment