Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (def div (fn [a b] (/ (double a) (double b))))
- (defn evaluate [this values]
- ((:evaluate this) values))
- (defn toString [this]
- (:toString this))
- (defn diff [this var]
- ((:diff this) var))
- (defn operation [op name]
- (fn [& operands]
- {
- :evaluate (fn [values] (apply op (map #((:evaluate %) values) operands)))
- :toString (str "(" name " " (clojure.string/join " " (map #(:toString %) operands)) ")")
- }))
- (defn Constant [val]
- {
- :evaluate (constantly val)
- :toString (str val)
- :diff (constantly (Constant 0))
- })
- (defn Variable [val]
- {
- :evaluate (fn [variables] (variables val))
- :toString val
- :diff (fn [var] (if (= val var)
- (Constant 1)
- (Constant 0)))
- })
- (def Add (operation + "+"))
- (def Subtract (operation - "-"))
- (def Multiply (operation * "*"))
- (def Divide (operation div "/"))
- (def Negate (operation - "negate"))
- (def ops
- {
- '+ Add,
- '- Subtract,
- '* Multiply,
- '/ Divide,
- 'negate Negate
- })
- (defn parse [expr]
- (cond
- (number? expr) (Constant expr)
- (symbol? expr) (Variable (str expr))
- (list? expr) (apply (ops (first expr)) (map parse (rest expr)))))
- (defn parseObject [expr] ((comp parse read-string) expr))
- (def expr (Variable "x"))
- (print (toString (diff expr "x")))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement