implement simplify

This commit is contained in:
2026-06-21 20:08:13 +02:00
parent b6779a930c
commit e7c500dbfa
+20 -2
View File
@@ -10,5 +10,23 @@
['* a (diff b var)]])
(errorf "unknown op: %v" op)))))
(pp (diff '(+ (* x x) 3) 'x))
(pp (diff '(+ x 3) 'x))
(defn simplify [expr]
(cond
(symbol? expr) expr
(number? expr) expr
(match expr [op & args]
(do
(def args (map simplify args))
(case op
'+ (do
(def terms (filter |(not= $ 0) args))
(if (= (length terms) 1) (first terms) ['+ ;terms]))
'* (cond
(find |(= $ 0) args) 0
(find |(= $ 1) args) (first (filter |(not= $ 1) args))
['* ;args]) # otherwise leave unchanged
[op ;args])))))
(pp (simplify (diff '(+ (* x x) 3) 'x)))
(pp (simplify (diff '(+ x 3) 'x)))