(ns de.skamphausen.stt13
  (:require [clojure.core.reducers :as r]))


(map inc (range 10))
;;=> (1 2 3 4 5 6 7 8 9 10)


(interleave [:a :b :c] (iterate inc 0))
;;=> (:a 0 :b 1 :c 2)
(map + [1 2 3] [10 20 30 40 50 60])
;;=> (11 22 33)


(def natz (iterate inc 1))
(time (nth natz 1000000))
;; "Elapsed time: 239.345539 msecs"
(time (nth natz 1000000))
;; "Elapsed time: 15.664133 msecs"


(defn pinc [i]
  (print (str "<" i ">"))
  (inc i))
(take 2 (map pinc (iterate inc 0)))
;; (<0><1>1 2) 
(take 2 (map pinc [1 2 3 4 5 6 7 8 9]))
;; (<1><2><3><4><5><6><7><8><9>2 3)


(defn podd? [i]
  (print (str "(" i ")"))
  (odd? i))

(take 2 (filter podd? (iterate inc 0)))
;; ((0)(1)(2)(3)1 3)
(take 2 (filter podd? (range 9)))
;; ((0)(1)(2)(3)(4)(5)(6)(7)(8)1 3)


(reduce + [1 2 3 4])
;;=> 10
(reduce (fn [acc x] 
          (assoc acc x (inc (get acc x 0)))) 
        {} "Hallo Welt") 
;;=> {\t 1, \e 1, \W 1, \space 1, \o 1, \l 3, \a 1, \H 1}
(reductions + [1 2 3 4])
;;=> (1 3 6 10)


(reduce + (map inc (filter odd? (range 10))))


(def zahlen (doall (range 1e7)))

(defn standard [daten]
  (reduce + (map inc
                 (filter odd? daten))))
(time (standard zahlen))
;; "Elapsed time: 1107.320599 msecs"
;;=> 25000005000000

(defn not-lazy [data]
  (reduce + (r/map inc
                   (r/filter odd? data))))
(time (not-lazy zahlen))
;; "Elapsed time: 687.40897 msecs"
;;=> 25000005000000


(defn mapping [map-fn]
  (fn [red-fn]
    (fn [acc element]
      (red-fn acc (map-fn element)))))
(reduce ((mapping inc) +) 0 [1 2 3])
;;=> 9


(seq (.getInterfaces
      (class (r/map inc [1 2]))))
(defn reducer
  ([coll xf] 
     (reify clojure.core.protocols/CollReduce
       (coll-reduce [_ f1 init]
         (clojure.core.protocols/coll-reduce coll (xf f1) init)))))


(defn parallel [data]
  (r/fold + (r/map inc
                   (r/filter odd? data))))
(time (not-lazy zahlen))
;; "Elapsed time: 699.521045 msecs"
(time (parallel zahlen))
"Elapsed time: 689.899531 msecs"

(def zahlen-v (vec zahlen))
(time (standard zahlen))   ;; "Elapsed time: 1021.680964 msecs"
(time (not-lazy zahlen))   ;; "Elapsed time: 705.568693 msecs"
(time (parallel zahlen))   ;; "Elapsed time: 693.122998 msecs"

(time (standard zahlen-v)) ;; "Elapsed time: 1054.37094 msecs"
(time (not-lazy zahlen-v)) ;; "Elapsed time: 723.872857 msecs"
(time (parallel zahlen-v)) ;; "Elapsed time: 205.894815 msecs"


(+)
;;=> 0
(= (+ 4 (+ 5 6)) (+ (+ 4 5) 6))



(defn freqs-fold [items]
  (r/fold
   (r/monoid (partial merge-with +)
             (constantly {}))
   (fn [acc el]
     (assoc acc el (inc (get acc el 0))))
   items))

(merge-with + {:a 2} {:a 4})
;;=> {:a 6}
((partial merge-with +) {:a 2} {:a 4})
;;=> {:a 6}


(def mo (r/monoid + (constantly 0)))

(mo)
;;=> 0
(mo 1 2)
;;=> 3
