I am a little confused about when to use or implement functors in one code. I have included some code below that has two display_expr, cal_expr functions, and both of these functions have the same form, but differ in implementation. Will this be the place where I would like to consider creating one functor, which will be the main functionality of both functions?
type expr = | Add of expr * expr | Minus of expr * expr | Multi of expr * expr | Divide of expr * expr | Value of int;; let rec display_expr e = match e with | Add (a1, a2) -> "(" ^ display_expr a1 ^ " + " ^ display_expr a2 ^ ")" | Minus (m1, m2) -> "(" ^ display_expr m1 ^ " - " ^ display_expr m2 ^ ")" | Multi (m1, m2) -> "(" ^ display_expr m1 ^ " * " ^ display_expr m2 ^ ")" | Divide (d1, d2) -> "(" ^ display_expr d1 ^ " / " ^ display_expr d2 ^ ")" | Value v -> string_of_int v;; let rec cal_expr e = match e with | Add (a1, a2) -> (cal_expr a1) + (cal_expr a2) | Minus (m1, m2) -> (cal_expr m1) - (cal_expr m2) | Multi (m1, m2) -> (cal_expr m1) * (cal_expr m2) | Divide (d1, d2) -> (cal_expr d1) / (cal_expr d2) | Value v -> v;; let equ = Multi(Value 34, Add(Value 24, Divide(Value 24, Minus(Value 10, Value 7) ) ) );; Printf.fprintf stdout "%d = %s\n" (cal_expr equ) (display_expr equ);;
Note. I tried to write a solution for the above code, and I got one working as soon as I found out that the functor required a common or combined type for the values ββreturned by display_expr and cal_expr.
Also: I am an extreme OCaml rookie, so please think about this in your answer. Thank you.
source share