Advertisement
Guest User

Untitled

a guest
May 5th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (def div (fn [a b] (/ (double a) (double b))))
  2.  
  3. (defn evaluate [this values]
  4.   ((:evaluate this) values))
  5.  
  6. (defn toString [this]
  7.   (:toString this))
  8.  
  9. (defn diff [this var]
  10.   ((:diff this) var))
  11.  
  12. (defn operation [op name]
  13.   (fn [& operands]
  14.     {
  15.      :evaluate (fn [values] (apply op (map #((:evaluate %) values) operands)))
  16.      :toString (str "(" name " " (clojure.string/join " " (map #(:toString %) operands)) ")")
  17.      }))
  18.  
  19. (defn Constant [val]
  20.   {
  21.    :evaluate (constantly val)
  22.    :toString (str val)
  23.    :diff     (constantly (Constant 0))
  24.    })
  25.  
  26. (defn Variable [val]
  27.   {
  28.    :evaluate (fn [variables] (variables val))
  29.    :toString val
  30.    :diff     (fn [var] (if (= val var)
  31.                          (Constant 1)
  32.                          (Constant 0)))
  33.    })
  34.  
  35. (def Add (operation + "+"))
  36. (def Subtract (operation - "-"))
  37. (def Multiply (operation * "*"))
  38. (def Divide (operation div "/"))
  39. (def Negate (operation - "negate"))
  40.  
  41. (def ops
  42.   {
  43.    '+      Add,
  44.    '-      Subtract,
  45.    '*      Multiply,
  46.    '/      Divide,
  47.    'negate Negate
  48.    })
  49.  
  50. (defn parse [expr]
  51.   (cond
  52.     (number? expr) (Constant expr)
  53.     (symbol? expr) (Variable (str expr))
  54.     (list? expr) (apply (ops (first expr)) (map parse (rest expr)))))
  55.  
  56. (defn parseObject [expr] ((comp parse read-string) expr))
  57.  
  58. (def expr (Variable "x"))
  59. (print (toString (diff expr "x")))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement