Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (defn constant [x] (fn [args] x))                              ;
  2. (defn variable [name] (fn [args] (args name)))              ;
  3. (defn unary-operation
  4.   [function]
  5.   (fn [operand]
  6.     (fn [vars] (function (operand vars)))))                 ;
  7. (defn opera
  8.   [f]
  9.   (fn [& operands]
  10.     (fn [vars] (apply f (mapv (fn [x] (x vars)) operands)))))
  11. (fn [& xs] (reduce (fn [a b] (if (< a b) b a)) (vector xs)))
  12. (def add (opera +))                                     ;
  13. (def subtract (opera -))                                ;
  14. (def multiply (opera *))                                ;
  15. (def divide (opera (fn [a b] (/ (double a) (double b))))) ;
  16. (def negate (unary-operation -))                                  ;
  17. (def square (unary-operation (fn [a] (* a a))))                        ;
  18. (def sqrt (unary-operation (fn [a] (Math/sqrt (Math/abs a)))))          ;
  19. (def maximal (opera (fn [& xs] (reduce (fn [a b] (if (< a b) b a)) xs))))                              ;
  20. (def minimal (opera (fn [& xs] (reduce (fn [a b] (if (> a b) b a)) xs))))                         ;
  21. (def Operators {
  22.                 '+ add '- subtract '* multiply '/ divide 'negate negate 'square square 'sqrt sqrt 'max maximal 'min minimal}) ;
  23. (defn parse [expr] (cond
  24.                      (seq? expr) (apply (Operators (first expr)) (mapv parse (rest expr)))
  25.                      (number? expr) (constant expr)
  26.                      :else (variable (str expr))))          ;
  27. (def parseFunction (comp parse read-string))                ;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement