(ns clojure-arithm-operations-clean-code)

      
      
;tool: absolute value 
;Shlomi (2016) 
;https://stackoverflow.com/questions/21753243/absolute-value-of-a-number-in-clojure
(defn abs [n] (max n (-' n)))

;;bank with the four oprations
(def my-operations   ["+" "-" "*" "/" ]); #'clojure-arithm-operations.core/my-operations

;; an operation is chosen at random
(defn choose-operation []
       "an operation is chosen at random"
       (my-operations (rand-int 4)))

; constant is defined
(def target-operation (choose-operation))

;seed-code to be evolved by hand is defined
(def seed-code1 '(+ 1 2))
(def seed-code2 "(+ 2 3)")

 ;target-operation is evaluated over x y
(defn result [target-operation x y]
 (let [code (clojure.string/replace "(plus six 2)" #"plus"    target-operation)
       code (clojure.string/replace code #"six"    x)
       code (clojure.string/replace code #"2"    y  )                           
       ]
   (println target-operation)
    (eval (binding [*read-eval* false] (read-string code)))))
 (result target-operation "8" "4");32
 
(defn matching-trial  [target-operation]
  "A trial operation is chosen at random. 
      Target and trial operation are compared by their outputs.
      Differences are added together to acc"
  (let
    [trial-operation (choose-operation)]
    (loop [iter 1
           acc  0]
      (if (> iter 20) (double  acc);return value
        (let [x (str (inc (rand-int 10)))
              y (str (inc (rand-int 10)))
              result1 (result target-operation x y)                
              result2 (result trial-operation x y) 
              difference (abs (- result1 result2))]
          (recur (inc iter) (+ acc difference)))))))
   

(defn report [target-operation times]
 (let [code "(defn matching-operation [x y]
              (plus x y))" ]
 (println "Target-operation " target-operation "   ERROR = 00000000000000000000000000000000000000  times" times)
 (println "The operation has been matched. \nThe corresponding Clojure code is " )
 (clojure.string/replace code #"plus"    target-operation))
 )
         
 (defn task [target-operation]
   (loop [times 1]
     (let [error (matching-trial target-operation)]
       (println str "Times " times  "Error " error)
     (if ( = error 0.0) (report target-operation   times)
      (recur (inc times))))))
 
 ;run with 
 (task target-operation);