Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (defn constant [x] (fn [args] x)) ;
- (defn variable [name] (fn [args] (args name))) ;
- (defn unary-operation
- [function]
- (fn [operand]
- (fn [vars] (function (operand vars))))) ;
- (defn opera
- [f]
- (fn [& operands]
- (fn [vars] (apply f (mapv (fn [x] (x vars)) operands)))))
- (fn [& xs] (reduce (fn [a b] (if (< a b) b a)) (vector xs)))
- (def add (opera +)) ;
- (def subtract (opera -)) ;
- (def multiply (opera *)) ;
- (def divide (opera (fn [a b] (/ (double a) (double b))))) ;
- (def negate (unary-operation -)) ;
- (def square (unary-operation (fn [a] (* a a)))) ;
- (def sqrt (unary-operation (fn [a] (Math/sqrt (Math/abs a))))) ;
- (def maximal (opera (fn [& xs] (reduce (fn [a b] (if (< a b) b a)) xs)))) ;
- (def minimal (opera (fn [& xs] (reduce (fn [a b] (if (> a b) b a)) xs)))) ;
- (def Operators {
- '+ add '- subtract '* multiply '/ divide 'negate negate 'square square 'sqrt sqrt 'max maximal 'min minimal}) ;
- (defn parse [expr] (cond
- (seq? expr) (apply (Operators (first expr)) (mapv parse (rest expr)))
- (number? expr) (constant expr)
- :else (variable (str expr)))) ;
- (def parseFunction (comp parse read-string)) ;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement