Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (defn abstractOperation [firstFunction secondFunction & arguments]
  2.   (fn [VARS]
  3.     (firstFunction secondFunction (map #(% VARS) arguments))))
  4.  
  5. (defn abstractUnaryOperation [function argument]
  6.   (fn [vars]
  7.     (function (argument vars))))
  8.  
  9. (defn variable [name] (fn [vars] (vars name)))
  10. (defn constant [arg] (constantly arg))
  11.  
  12. (def divide (partial abstractOperation reduce #(/ %1 (double %2))))
  13. (def multiply (partial abstractOperation apply *))
  14. (def subtract (partial abstractOperation apply -))
  15. (def add (partial abstractOperation apply +))
  16. (def negate (partial abstractUnaryOperation -))
  17. (def square (partial abstractUnaryOperation #(* % %)))
  18. (def sqrt (partial abstractUnaryOperation #(Math/sqrt (Math/abs %))))
  19.  
  20. (def variables
  21.   {'x (variable "x")
  22.    'y (variable "y")
  23.    'z (variable "z")})
  24.  
  25. (def operations
  26.   {'+      add
  27.    'negate negate
  28.    '-      subtract
  29.    '*      multiply
  30.    '/      divide
  31.    'square square
  32.    'sqrt   sqrt})
  33.  
  34. (defn parse [expression]
  35.   (cond
  36.     (list? expression)
  37.     (apply (operations (first expression))
  38.            (map parse (rest expression)))
  39.     (number? expression) (constant expression)
  40.     (contains? variables expression) (variables expression)
  41.     (contains? operations expression) (operations expression)))
  42.  
  43. (defn parseFunction [expression]
  44.   (parse (read-string expression)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement