Advertisement
IzhanVarsky

Untitled

Apr 28th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. (defn operator [action]
  2. (fn [& operands]
  3. (fn [map] (apply action (mapv #(% map) operands)))))
  4.  
  5. (def myMinMax #(fn rec
  6. ([a] a)
  7. ([a b] (if (% a b) a b))
  8. ([a b & more] (apply rec (rec a b) more))))
  9.  
  10. (def add (operator +))
  11. (def subtract (operator -))
  12. (def multiply (operator *))
  13. (def divide (operator (fn
  14. ([a b] (/ (double a) b))
  15. ([a b & more] (apply divide (divide a b) more)))))
  16. (def negate (operator -))
  17. (def sqrt (operator #(Math/sqrt (Math/abs (double %)))))
  18. (def square (operator #(* % %)))
  19. (def max (operator (myMinMax >)))
  20. (def min (operator (myMinMax <)))
  21. (def med (operator #(nth (sort %&) (/ (count %&) 2))))
  22. (def avg (operator #(/ (apply + %&) (count %&))))
  23. (def constant #(fn [_] %))
  24. (def variable #(fn [map] (get map %)))
  25.  
  26. (def fun-operations {'+ add
  27. '- subtract
  28. '* multiply
  29. '/ divide
  30. 'negate negate
  31. 'sqrt sqrt
  32. 'square square
  33. 'min min
  34. 'max max
  35. 'med med
  36. 'avg avg})
  37.  
  38. (defn parseList [s]
  39. (if (list? s)
  40. (apply (get fun-operations (first s)) (map parseList (rest s)))
  41. (if (number? s)
  42. (constant s)
  43. (variable (str s)))
  44. )
  45. )
  46. (def parseFunction #(parseList (read-string %)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement