leibniz/examples/tier1.ml
2026-01-19 03:37:26 +00:00

50 lines
1.7 KiB
OCaml

open Leibniz
let () =
print_endline "polynomial expansion and collection\n";
let expr = Parser.parse "(x + 1)^3" in
let expanded = Polynomial.expand expr in
print_endline ("expanded: " ^ Expr.to_string expanded);
print_endline "\ncommon subexpression elimination\n";
let complex_expr = Parser.parse "sin(x + y) * cos(x + y) + sin(x + y)" in
let cse_result = Cse.common_subexpression_elimination complex_expr in
print_endline ("original: " ^ Expr.to_string complex_expr);
List.iter (fun (name, e) ->
print_endline (Printf.sprintf "%s = %s" name (Expr.to_string e))
) cse_result.subexpressions;
print_endline ("final: " ^ Expr.to_string cse_result.final_expr);
print_endline "\ncode generation to C\n";
let f = Parser.parse "x^2 + sin(y) * cos(z)" in
let c_code = Codegen.compile_to_c f ["x"; "y"; "z"] in
print_endline c_code;
print_endline "horner form optimization\n";
let poly = Parser.parse "x^4 + 2x^3 + 3x^2 + 4x + 5" in
let horner = Cse.horner_form poly "x" in
print_endline ("horner form: " ^ Expr.to_string horner);
print_endline "\nlimits computation\n";
let limit_expr = Parser.parse "(sin(x)) / x" in
(match Limits.limit limit_expr "x" (Expr.Const 0.0) Limits.Bidirectional with
| Some result -> print_endline ("lim (sin(x)/x) as x→0 = " ^ Expr.to_string result)
| None -> print_endline "limit could not be computed");
print_endline "\nsymbolic matrix operations\n";
let m = Matrix.create 2 2 (fun i j ->
if i = j then Expr.Var (Printf.sprintf "a%d%d" i j)
else Expr.Var (Printf.sprintf "a%d%d" i j)
) in
let det_m = Matrix.det m in
print_endline ("det = " ^ Expr.to_string det_m);
let trace_m = Matrix.trace m in
print_endline ("trace = " ^ Expr.to_string trace_m)