Advertisement
Guest User

Untitled

a guest
Oct 30th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (defn operationFactory [operator]
  2.   (fn operation [leftExpr rightExpr]
  3.     (fn [args]
  4.       (operator (leftExpr args)
  5.                 (rightExpr args))
  6.       )))
  7.  
  8. (defn unaryOperationFactory [operator]
  9.   (fn operation [Expr]
  10.     (fn [args]
  11.       (operator (Expr args))
  12.       )))
  13.  
  14. (defn constant [val]
  15.   (fn [args] (double val)))
  16.  
  17.  
  18. (defn variable [name]
  19.   (fn [args] (args name)))
  20.  
  21. (def multiply (operationFactory *))
  22. (def add (operationFactory +))
  23. (def subtract (operationFactory -))
  24. (defn divide [leftExpr rightExpr]
  25.   (fn [args]
  26.     (/ (double (leftExpr args))
  27.        (double (rightExpr args)))
  28.     ))
  29.  
  30. (def cosh (unaryOperationFactory 'Math/cosh))
  31. (def negate (unaryOperationFactory -))
  32. (def sinh (unaryOperationFactory 'Math/sinh))
  33. (def sin (unaryOperationFactory 'Math/sin))
  34. (def cos (unaryOperationFactory 'Math/cos))
  35.  
  36. (def op {'+    add, '- subtract, '* multiply, '/ divide,
  37.          'sinh sinh, 'cosh cosh, 'sin sin, 'cos cos, 'negate negate
  38.          })
  39.  
  40. (defn doParseFunction [expression]
  41.   (cond
  42.     (seq? expression) (apply (op (first expression)) (map doParseFunction (rest expression)))
  43.     (number? expression) (constant expression)
  44.     (symbol? expression) (variable (str expression))
  45.     )
  46.   )
  47.  
  48. (defn parseFunction [expression]
  49.   (doParseFunction (read-string expression))
  50.   )
  51.  
  52. (def expr (parseFunction "(sinh (- x y))"))
  53. (sinh (subtract (variable "x") (variable "y")))
  54. (print (expr {"z" 0.0, "x" 0.0, "y" 0.0}))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement