;An arithmetic operation is chosen at random 
;and a match is found by code generation.
;idiomatic version

(ns clojure-arithm-operations.pro)


;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 arithmetic operators
(def ops   '[+ - * /])

;; an operation is chosen at random
(defn choose-operator []
       "an operation is chosen at random"
      (nth ops (rand-int (count ops))))

(comment
  ;Adapted from:
  ;Brian Carper (2009)
  ;Code Generation in Clojure
  ;https://stackoverflow.com/questions/1627625/code-generation-in-clojure
  (defn foo []
    "A random operator is chosen at random and tested over random data"
     (let [ops '[+ - * /]               ; SO's lisp-highlighting sucks
           nums (repeatedly #(inc (rand-int 5)))
           expr (list* (nth ops (rand-int (count ops))) (take 10 nums))]
       (prn expr)
       (prn (eval expr))))
  
(foo); (- 3 5 3 4 1 4 5 2 3 5) -29
(foo); (- 2 3 1 4 4 3 4 3 2 1) -23
(foo); (- 3 4 1 5 3 1 2 3 4 2) -22
(foo); (* 2 4 2 5 2 5 1 5 4 1) 16000
(foo); (+ 3 5 5 1 3 4 2 1 1 4) 29
(foo); (* 5 2 2 1 1 3 5 2 2 2) 2400
(foo); (/ 2 4 3 4 2 1 2 2 4 2) 1/1536
(foo); (* 3 5 3 5 2 4 2 2 4 2) 57600
 )



(defn matching-trial  [target-operation]
  "A trial operation is chosen at random. 
   Target and trial operation are compared by their outputs."
  (let [ops '[+ - * /]               ; SO's lisp-highlighting sucks
        nums (repeatedly #(inc (rand-int 5)))
        trial-op (nth ops (rand-int (count ops)))
        data (take 10 nums)
        trial-expr (list* trial-op data)
        trial-result (eval trial-expr)
        target-expr (list* target-operation data) 
        target-result (eval target-expr)
        difference (abs (- trial-result target-result)) ]
        (print trial-expr)
        (println (eval trial-expr))
        (print target-expr)
        (println(eval target-expr))
        
        difference (abs (- trial-result target-result))
        ))



(defn report [target-operation times]
 (let [code1 "(defn matching-operation [x y] \n (" 
       code2 "x y))" ]
			 (println "Target-operation " target-operation "   ERROR = 00000000000000000000000000000000000000  times" times)
			 (println "The operation has been matched. \nThe corresponding Clojure code is " )
			 (println str "\n"   code1 target-operation code2)))


(defn task []
   (loop [times 1]
     (let [target-operation (choose-operator)
           error (matching-trial target-operation)]
		       (println (str "Times " times  " Error " error "\n"))		       
		       (if ( = error 0) (report target-operation   times)
                            (recur (inc times))))))

;run with 
 (task)