Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (defn evaluate [expr vars] ((.evaluate expr) vars))
- (defn toString [expr] (.toStr expr))
- (defn diff [expr var] ((.diff expr) var))
- ;Interface
- (definterface Operation
- (evaluate [])
- (toStr [])
- (diff []))
- ;Const
- (declare Constant)
- (deftype Const [value]
- Operation
- (evaluate [this] (fn [vars] value))
- (toStr [this] (format "%.1f" (double value)))
- (diff [this] (fn [var] (Constant 0))))
- (defn Constant [val] (Const. val))
- (deftype Var [name]
- Operation
- (evaluate [this] (fn [args] (get args name)))
- (toStr [this] name)
- (diff [this] (fn [args] (if (= args name) (Constant 1) (Constant 0)))))
- (defn Variable [name] (Var. name))
- (deftype OperationPrototype [op symbol howToDiff])
- (deftype MakeOperation [prot args]
- Operation
- (evaluate [this] (fn [args] (apply (.op prot) (map (fn [x] (evaluate x args)) args))))
- (toStr [this] (str "(" (.symbol prot) " " (clojure.string/join " " (map toString args)) ")"))
- (diff [this] (fn [args] (apply (.howToDiff prot) (concat args (map (fn [x] (diff x args)) args))))))
- (declare Add)
- (def AddProt (OperationPrototype.
- +
- "+"
- (fn [a b da db] (Add da db))))
- (defn Add [& ar]
- (MakeOperation. AddProt ar))
- (declare Subtract)
- (def SubProt (OperationPrototype.
- -
- "-"
- (fn [a b da db] (Subtract da db))))
- (defn Subtract [& ar]
- (MakeOperation. SubProt ar))
- (declare Multiply)
- (def MultiplyProt (OperationPrototype.
- *
- "*"
- (fn [a b da db] (Add (Multiply da b) (Multiply a db)))))
- (defn Multiply [& ar]
- (MakeOperation. MultiplyProt ar))
- (declare Divide)
- (def DivideProt (OperationPrototype.
- (fn [x y] (/ (double x) (double y)))
- "/"
- (fn [a b da db] (Divide (Subtract (Multiply da b) (Multiply a db)) (Multiply b b)))))
- (defn Divide [& ar]
- (MakeOperation. DivideProt ar))
- (declare Negate)
- (def NegateProt (OperationPrototype.
- -
- "negate"
- (fn [a da] (Negate da))))
- (defn Negate [& ar]
- (MakeOperation. NegateProt ar))
- (def operationsMap {"+" Add,
- "-" Subtract,
- "*" Multiply,
- "/" Divide,
- "negate" Negate})
- (def vars {'x (Variable "x"),
- 'y (Variable "y"),
- 'z (Variable "z")})
- (defn parse [expression]
- (cond
- (symbol? expression) (get vars expression)
- (number? expression) (Constant expression)
- :else (let [op (first expression) args (rest expression)] (apply (get operationsMap (str op)) (map parse args)))))
- (defn parseObject [expression] (parse (read-string expression)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement