(ns my-first-project.core)

;This is a library of programs in Clojure
;for REPL under Eclipse + CounterClockWise.

;To open REPL: right click on this window
;and select 
Leiningen $->$ Launch headless REPL for the project.

;To stop a calculation: click on the cogwheel icon
;to clean the output console: click on the icon with a screen with an x.

;Extracted from:

;Hirokuni Kim (2017)
;Clojure by example
;https://kimh.github.io/clojure-by-example/#about
(println "Hello, world!")
"h"
100
(type 'a)

; Bindings
(def a "aaaaa")
(println a)

;let
(let [l "light"] (println (str "God said let there be " l)))
(println l); l is local, private.

(let [l "light"
             d "darkness"]
             (println (str "God said let there be " l))
             (println (str "God also said let there be " d)))

(let [l "light"
            l_d (str l " and" " darkness")]
            (println (str "God also said let there be " l_d)))


;Scope

(let [a "aaa"]
        (println a))


(let [a "aaa"]
        (let [a "AAA"]
          (println a)))

(let [a "a"]
        (let []
          (println a)))

(let [a "a"]
        (let []
          (println not-bound-symbol)))

;Def:  must be avoided. It is as a global variable.
(def object "light")
(println (str "God said let there be " object))
:overridig
(def object "darkness")
(println (str "God said let there be " object))

; Functions

(defn say-hello
         [name]
         (println (str "Hello, " name)))
(say-hello "Kim")

;Documentation can be included:
(defn say-hello
         "Takes name argument and say hello to the name"
         [name]
         (println (str "Hello, " name)))
;Print documentation: where is doc?
(doc say-hello)

;Metadata + doc
(defn say-hello
         "Takes name argument and say hello to the name"
         {:added "1.0"
          :static true}
         [name]
         (println (str "Hello, " name)))
(meta (var say-hello))
;variant:
(meta #'say-hello)

;Anonymous Function
;creation:
(fn [] (println "Hello world"))
;binding
(def hello-world-func (fn [] (println "Hello world")))
(hello-world-func)

#() shortcut for fn
#(+ 1 1)
#<core$eval8112$fn__8113 my_first_project.core$eval8112$fn__8113@48ed1e>

; % = argument passed to the function
(let [plus #(+ 1 %)]
         (plus 10)); 11

(let [plus-numbers #(+ 1 %1 %2 %3)]
         (plus-numbers 10 20 30));61

;Passing a function to another function
(def say-hello (fn [name] (println (str "Hello, " name))))
   (def say-bye (fn [name] (println (str "Good bye, " name))))
   (def greeting (fn [greeting-func name] (greeting-func name)))
   (greeting say-hello "Kim")
   (greeting say-bye "Kim")
   
	; Closure
	(defn inner
	            [from-outer]
	            (fn [] (println from-outer)))
	   
   (def outer1 (inner "this is from outer"))
   
   (def outer2 (inner "this is yet another from outer"))
   
   (outer1)
   (outer2)

   
   ;Namespaces: my.app.example. Similar to  Java classes
   ;; Clojure recommends namespaces be at least "two segments" (ie, they should
   ;; have at least one '.') otherwise it will create a class in the "default
   ;; package", which is discouraged.
   (create-ns 'clojure.by.example); single quote = no evaluation
   (ns my-new-namespace); to switch to  a namespace
   *ns*; which namespace
   
   ;Namespaces are territorial
   (defn favorite-language [] "Clojure!!")
   (favorite-language)
   (in-ns 'user)
   (favorite-language)
   
   
   ;Import
   (import java.util.Date)
   (new Date)
   
   ;Ns (Namespace)
   (ns example.namespace
  (:require [clojure.java.io])
  (:use [clojure.data])
  (:import [java.util List Set]))
   
   ;Control flow
   
   ;if
   (if true
         (println "This is always printed")
         (println "This is never printed"))
   
   (if true
         (do; various commands
         (println "one")
         (println "two")))
   
   ;If-let
   (defn positive-number-seq [numbers]
            (if-let [pos-nums (seq (filter pos? numbers))]
             pos-nums;  = name of output
             "no positive numbers")); else
   (positive-number-seq [-1 -2]);no positive numbers
   (positive-number-seq [-1 -2 4 5]);(4 5)
   (positive-number-seq []) ;no positive numbers
   
   ;When
   (when true
         (println "one")
         (println "two"))
   
   ;When-let
   (when-let [pos-nums (filter pos? [ -1 -2 1 2])]
          pos-nums
          (println "one")
          (println "two"))
   
   ;Case
   (defn case-test-1
         [n]
         (case n
            1 "n is 1"
            2 "n is 2"
            "n is other"))
   
   (println (case-test-1 1))
   (println (case-test-1 2))
   (println (case-test-1 3))
   
   ;Cond (conditional)
   (defn cond-test
         [n]
         (cond
           (= n 1) "n is 1"
           (and (> n 3) (< n 10)) "n is over 3 and under 10"
           :else "n is other"))
   (println (cond-test 1))
   (println (cond-test 5))
   (println (cond-test 15))
   
   ;Condp = condition in predicate
   (defn condp-test-2
         [n]
         (condp contains? n
           [1 2 3] "n is either 1 or 2 or 3"
           "n is not 1 or 2 or 3"))
   (println (condp-test-2 2))
   (println (condp-test-2 5))
   
   ;Boolean. Everything except false and nil are true.
   (boolean false)
   (boolean nil)
   (boolean 0)
   (boolean 1)
   (boolean "hi there")
   (boolean :hi)
   
   :str
   (str "Good " "morning")
   (+ "Good " "morning");this does not function
   
   (let [first "Hirokuni"
               last "Kim"]
               (str "My name is " first " " last))
   
   ; %s = string;%d integer; %.Nf # of floating synbols; %b boolean
   (format "My name is %s %s" "Hirokuni" "Kim")
   (format "I ate %d apples" 2)
   (format "Pi: %.3f" 3.14159265)
   (format "Pi: %.5f" 3.14159265)
   (format "Boolean representation of 1: %b" 1)
   (format "Boolean representation of nil: %b" nil)
   
   
   ;Integers
   (+ 2 3)
   (- 10 3)
   (* 10 2)
   (/ 4 2)
   (/ 4 3)
   (mod 3 2); 1
   (max 1 2 3 4 5)
   (min 5 4 3 2 1)
   ;Power but without for-loops:
   ;reduce takes a sequence generated by repeat 
   ;and compute * against each element of the sequence
   ;and returns the output. 
   ;The output is used to do * against the next element of the sequence.
   (defn power
     [x n]
     (reduce * (repeat n x))
   )
   (power 2 3); 2 to power 3 = 8
   
   ;Bigint. Marked with N
   (+ (bigint Long/MAX_VALUE) 10); 9223372036854775817N
   (+ 9223372036854775807N 10N)
   
   ;List
   '(1 2 3)
   (nth '(1 2 3) 1); 2. Countingbegins with 0.
   (count '(1 2 3) )
   (conj '(1 2 3) 4); (4 1 2 3)!!!
   
   ;There is no remove from list. Use a vector or  set
   
   ;Vectors
   [1 2 3]
   (nth [1 2 3] 1); 2
   (first [1 2 3]);1
   (second [1 2 3]);2
   (last [1 2 3]);3
   (conj [1 2 3] 4); [1 2 3 4]!!!
   (.indexOf [1 2 3] 2); 1
   (.indexOf [1 2 3] 4); -1
   
   ;Sets: order is not guaranteed: #{}
   #{1 2 3}
   (conj #{1 2 3} 4); #{1 4 3 2}
   (conj (conj #{1 2 3} 4) 4); #{1 4 3 2}
   (sort (conj #{1 3 2} 4)); (1 2 3 4) not a set. An array sequence:
   (type (sort (conj #{1 3 2} 4))); clojure.lang.ArraySeq
   
   ;Disj = disj-oin = A-{b}
   (disj #{1 2 3} 1); #{3 2}
   (disj #{1 2 3} 4); #{1 3 2}
   ;Select = filter
   (clojure.set/select odd? #{1 2 3} );#{1 3}
   (contains? #{1 2 3} 1);true
   (contains? #{1 2 3} 4);false
   (clojure.set/subset? #{1 2} #{1 2 3 4});true
   (clojure.set/subset? #{1 5} #{1 2 3 4});false
   (clojure.set/superset? #{1 2 3} #{1 2});true
   
   ;Maps: key-value data structures: {}
   {"Apple" "Mac" 
    "Microsoft" "Windows"}

   (get {"Apple" "Mac" 
        "Microsoft" "Windows"} "Apple"); Mac
   (get {"Apple" "Mac" 
         "Microsoft" "Windows"} "Linux");nil
   ;optional symbols : ,
   (:Apple {:Apple "Mac" :Microsoft "Windows"});Mac
   ;Add new pair
   (assoc {"Apple", "Mac" "Microsoft" "Windows"} "Commodore" "Amiga")
   ;overriding
   (assoc {"Apple", "Mac" "Microsoft" "Windows"} "Apple" "iOS")
   ;{"Apple" "iOS", "Microsoft" "Windows"}
   
   (merge {"Apple", "Mac" "Microsoft" "Windows"} {1 2})
   ;{1 2, "Apple" "Mac", "Microsoft" "Windows"}

   (keys {"Apple", "Mac" "Microsoft" "Windows"})
   ;("Apple" "Microsoft")
   
   (vals {"Apple", "Mac" "Microsoft" "Windows"})
   ;("Mac" "Windows")
   
   ;Sequences 
   ;are logical lists that are not tied to a particular implementation.
   (map inc [ 1 2 3 ]);(2 3 4)
   (map inc `( 1 2 3 ));(2 3 4)
   (map inc #{ 1 2 3 });(2 4 3)
   
   (map println {:a 1 :b 2 :c 3} )
   ;[:c 3]
   ;(nil[:b 2]
   ; nil[:a 1]
   ;nil)
   
   (type (map inc [ 1 2 3 ]));clojure.lang.LazySeq
   
   (map (fn [x] (+ x 1)) '(1 2 3));(2 3 4)
   
   ;reduce
   ;boils down values in a collection 
   ;into a single value by applying a function.
   (reduce + [1 2 3 4]);10
   
   ;You can pass a default value in the second argument. 
   ;When default value is given, 
   ;reduce will use it as a starting point.
   (reduce + 2 [1 2 3 4]);12
   (reduce + -10 [1 2 3 4]);0
   
   ;into
   ;to convet from one type of collection to another
   (into [] `(1 2 3));[1 2 3]
   (into (list) [1 2 3]);(3 2 1)
   (into #{} [1 2 3]);#{1 3 2}
   (into [] #{1 2 3});[1 3 2]
   
   (into {} [[:a 1] [:b 2] [:c 3]])
   ;{:a 1, :b 2, :c 3}
   (into [] {:a 1 :b 2 :c 3})
   ;[[:c 3] [:b 2] [:a 1]]
   
   ;into = reduce + conj
   (reduce conj #{} [1 2 3]);#{1 3 2}
   (reduce conj () [1 2 3]);(3 2 1)
   
   (reverse [1 2 3]);(3 2 1)
   
   ;iterate = crash
   ; returns an infinite sequence of ints
   (reverse (iterate + 0)
    (range 5 10);(5 6 7 8 9)
    (repeatedly 5 (fn [] (println "hi!")) );hi 5 times + nil
  
    ;Doseq = do to each element of the sequence == for-each
    ;Clojure doesn’t have for or for-each. 
    ;Do something to each element of a sequence, use doseq.
    (doseq [animal ["cat" "dog" "horse"]] (println animal) )
     ;cat dog horse + \cr
   
     (doseq [n1 [1 2 ]
                 n2 [4 5 ]]
           (println (+ n1 n2))); operates over A x B = 5 6 6 7 nil

      
     (take 5 (range 0 100));(0 1 2 3 4)
     (take-while neg? [-3 -2 -1 0 1 2 3 -5 -6]);(-3 -2 -1)
      
     (select neg? [-3 -2 -1 0 1 2 3 -5 -6]);XXXXXXXXX
      
     ;remove first 5
     (drop 5 (range 0 10));(5 6 7 8 9)
      
     (drop-while neg? [-3 -2 -1 0 1 2 3 -5 -6]);(0 1 2 3 -5 -6)
     (concat '(1 2 3) '(4 5 6)); (1 2 3 4 5 6)
      
     ;cons
     ; to create a new seq with a const inserted at the head of the sequence
     (cons 0 '(1 2));(0 1 2)
      
     (def old-seq '(1 2))
     (def new-seq (cons 0 old-seq))
		  old-seq; (1 2)
		  new-seq; (0 1 2);
     
    (partition-by #(< 3 %) [1 2 3 4 5 6]);((1 2 3) (4 5 6))
     
    (group-by #(< 3 %) [1 2 3 4 5 6 1 2 3])
    ;{false [1 2 3 1 2 3], true [4 5 6]} This is a map
     
    ;Lazy sequence
    (println (iterate inc 0)); infinite sequence. Stop with the cogwheel.
     
    (println (take 5 (iterate inc 0))) ;(0 1 2 3 4) nil
     
     
    ;:when = evaluate when true
    ;{x|  x > 0}
     (for [x '(-1 1 2) :when (< 0 x)] x); (1 2)
      
     (for [x [0 1 2 3 4 5]
               :let [y (* x 3)]
               :when (even? y)]
           y) ; (0 6 12)
      
      
     ;stops on the first false
     (for [x (range 10) :while (not= x 5)]
        x); (0 1 2 3 4)
      
     (for [x ['a 'b 'c]
            y [1 2 3]]
       [x y])
      
     ;A x B 
     (for [x ['a 'b 'c]
               y [1 2 3]]
          [x y])
			;([a 1] [a 2] [a 3]  [b 1] [b 2]  [b 3]  [c 1]  [c 2] [c 3])
   
   ;Recursion
   (defn fibo-recursive [n]
         (if (or (= n 0) (= n 1))
           n
           (+ (fibo-recursive (- n 1)) (fibo-recursive (- n 2)))))
      (fibo-recursive 0);0
      (fibo-recursive 6);8
      
    (defn fibo-recur [iteration]
        (let [fibo (fn [one two n]
          (if (= iteration n)
            one
            (recur two (+ one two) (inc n))))]
          ;; 0N 1N are bigint literals. See Bigint section
          ;; We need to use bigint to avoid StackOverflow to do the addition of big Fibonacci numbers
          ;; demonstrated below.
          (fibo 0N 1N 0)))
    
    ;recur re-binds it’s arguments to new values 
    ;and call the function with the new values.
     (defn fibo-recur [iteration]
           (let [fibo (fn [one two n]
             (if (= iteration n)
               one
               (recur two (+ one two) (inc n))))]
             ;; 0N 1N are bigint literals. See Bigint section
             ;; We need to use bigint to avoid StackOverflow to do the addition of big Fibonacci numbers
             ;; demonstrated below.
             (fibo 0N 1N 0)))
     (fibo-recur 6); 8N
 
 
     ;to avoid stackoverflow:
     ;recur  will keep calling count-down function with updated arguments 
     ;until n becomes 0.
     (defn count-down [result n]
           (if (= n 0)
             result
             (recur (conj result n) (dec n))))
   (count-down [] 5);[5 4 3 2 1]
   
   ;tail recursion
   ;A function is tail recursive when the recursion 
   ;is happening at the end of it’s definition. Counterexample:error
   (defn fibo-loop-recur [current next iteration]
           (if (= 0 iteration)
           current
           (+ 0
             (recur next (+ current next) (dec iteration)))))
   ;Example
   (fibo-recur 100000); large N
   
   ;Loop (simulated) is used with recur
   (defn count-up [max]
           (loop [count 0]
             (if (= count max)
               (println "Done!")
               (do
                 (println (str "Counting " count))
                 (recur (inc count))))))
   
   (count-up 5); Counting 0 ...4 Done!
   
   ;equivalent code
   (defn count-up-no-loop [count max]
   (if (= count max)
     (println "Done!")
     (do
       (println (str "Counting " count))
       (recur (inc count) max))))
    (count-up-no-loop 0 5); Counting 0 ...4
   
   
   
   
   
    ;Macros = personaliztion of Clojure
   
    ;defmacro
    (defmacro unless [test then]
               "Evaluates then when test evaluates to be falsey"
               (list 'if (list 'not test)
                then))
    (unless false (println "false!!"));false!! nil
   
    ;Without quotes, you will see an exception
    (defmacro unless [test then]
               "Evaluates then when test evaluates to be falsey"
               (list if (list not test)
                then)); Exception
   
    ;expand macro
    (macroexpand '(unless false (println "hi")))
    ;(if (not false) (println "hi"))
   
    ;quote = '
    (quote (+ 1 2));(+ 1 2)
    (require 'clojure.string);nil  ' is necessary
   
    '(dec (inc 1)); (dec (inc 1))
    `(dec (inc 1));(clojure.core/dec (clojure.core/inc 1))
   
    '(+ 1 ~(inc 1));(+ 1 ~(inc 1))
    `(+ 1 ~(inc 1));(clojure.core/+ 1 2)
    '(+ 1 ~(inc 1));(+ 1 ~(inc 1))
   
    `(+ ~(list 1 2 3));(clojure.core/+ (1 2 3))
    `(+ ~@(list 1 2 3));(clojure.core/+ 1 2 3)
   
   
   
    ;Threading macros different than Java threads
    ; -> thread-first
   
    (conj (conj (conj [] 1) 2) 3);[1 2 3]
   
    (-> []
              (conj 1)
              (conj 2)
              (conj 3));[1 2 3]
   
     ;->> Thread-last
     (->> ["Japan" "China" "Korea"]
            (map clojure.string/upper-case)
            (map #(str "Hello " %))) 
     ;("Hello JAPAN" "Hello CHINA" "Hello KOREA")
    
    (->> (range 0 20)
      (map #(* % %))
      (filter even?)
      (take 10)
      (reduce +)) ; 1140
   
   
    (->> (range )
         (map #(* % %))
         (filter even?)
         (take 10)
         (reduce +)); 1140
   
   
    ;Delays evaluation
    (def later (do [] (prn "Adding") (+ 1 2))); "Adding"
    (def later (delay (do [] (prn "Adding") (+ 1 2))))
    ;#'my-first-project.core/later
   
    (def later (delay (do [] (prn "Adding") (+ 1 2))))
    (force later); 3
   
    (def later (fn [] (prn "Adding") (+ 1 2) ))
    (force later);#<core$later my_first_project.core$later@37669ab8>
   
    ;Futures
    (do
          (Thread/sleep 3000)
          (println "hello")); after 3 seconds: "hello"
   
    (do
           (future
           (Thread/sleep 3000)
           (println "after sleep"));after 3 seconds
           (println "hello"));now
    ;deref-erence
    (let [future-val (future (inc 1))]
             (println (deref future-val))); 2 nil

    (let [future-val (future (inc 1))]
          (println @future-val));2 nil
   
    @(future (Thread/sleep 3000) "returned!")
    ;returned! (after 3 seconds)
   
    (deref (future (Thread/sleep 1000) "I made it!") 2000 "Can't wait anymore!")
    ;I made it!
   
    (deref (future (Thread/sleep 3000) "I made it!") 2000 "Can't wait anymore!")
    ;Can't wait anymore! (after 2 seconds)
   
    (let [sleep-and-wait
             (map (fn [time]
               (future
                 (Thread/sleep time)
                 (print;n (str "slept " time " sec" ))))
                   [1000 2000])]
         (doall (map deref sleep-and-wait))
         (println "done"))
		 ;slept 1000 sec
		 ;slept 2000 sec
		 ;done
		 ;nil
  
   ;Realized? (Is future done?
   (def my-future (future (Thread/sleep 5000) ))
   (repeatedly 6
           (fn []
           (println (realized? my-future))
           (Thread/sleep 1000)))
		 ;true
		 ;(niltrue
		 ; niltrue
		  ...
		  nil)
                  
    ;Promises
    (def my-promise (promise))
    (def listen-and-callback (fn []
   (println "Start listening...")
   (future (println "Callback fired: " @my-promise))))
                  
    (defn do-time-consuming-job []
   (Thread/sleep 5000)
   (deliver my-promise "delivered value"))
    (listen-and-callback) (do-time-consuming-job)
    ;Callback fired:  delivered value... (after 5 seconds)
   
    ;Atoms
    (def atom-str (atom "hello"))
    (def atom-vector (atom [1 2 3]))
    (def atom-map (atom {:a "aaa" :b "bbb"}))
    (def atom-int (atom 53))
    (deref atom-int);53
    @atom-int;53
   
   
    ;Reset. Atoms are mutable
    (def atom-int (atom 53))
    ;#'user/atom-int

		 (reset! atom-int 35);35
		
		 @atom-int;35

   (reset! atom-int 100)
   ;100
   @atom-int
   ;100

   (reset! atom-int 200)
   ;200

   @atom-int;200
  
   ;Swap
   (def atom-int (atom 0))
   ;#'user/atom-int

   (swap! atom-int
     (fn [current-atom]
         (inc current-atom)))
   ;1

   (swap! atom-int
     (fn [_]
         "not int"))
   ;"not int"

   @atom-int ;"not int"




   ;The function that you pass to swap! will take an argument
   ;which is the current atom.
   ;The atom is updated by the return value of the function.
   (def atom-int (atom 100))
   ;#'user/atom-int
	(defn multiple-by
	[current-atom num]
	(* current-atom num))

 (swap! atom-int multiple-by 10); 1000

   (def x 0)
   (repeatedly 10
     (fn [] (def x (inc x))))
    x; 10
    
    ;future os not thread safe
    (repeatedly 10
        (fn [] (future (def x (inc x)))))
    x; sometimes 5 others 3...20
    
    (def x (atom 0))
    (repeatedly 10
        (fn [] (future (swap! x inc)))); 1, 2... 10
    
    ;refs= manage multiple states
    (def my-ref (ref 0))
    (deref my-ref);0
    @my-ref;0
    
    ;Do-sync
    (deref my-ref);0
    @my-ref;0
    (dosync
       (ref-set my-ref 1)
       (ref-set my-ref 2));2
    @my-ref;2
    (ref-set my-ref 3);error: dosync is lacked
    
    ;Alter
    (def my-ref (ref 0))
    (dosync
        (alter my-ref
        (fn [current_ref]
            (inc current_ref)))); 1
    
    (dosync
        (alter my-ref
          (fn [_] "not int")));not-int
    
    (def my-ref (ref 100))
    (defn multiple-by
        [current-ref num]
        (* current-ref num))
    (dosync
        (alter my-ref multiple-by 10));1000
    
    ;Transaction
    (def my-ref (ref 0))
   (future
     (dosync
       (alter my-ref inc)
       (Thread/sleep 5000)))
   (println @my-ref);0
   ;; Wait 5 seconds
   (println @my-ref);0
    
    ;Java interop
    (new java.util.Date)
    (new java.util.Date "2016/2/19")
    ;#inst "2016-02-19T05:00:00.000-00:00"
    (java.util.Date.); date of today now
    (java.util.Date. "2016/2/19")
    (let [current_date (new java.util.Date)]
        (println current_date))
    ;#inst "2017-05-11T21:53:25.398-00:00"
    
    (Math/pow 2 3);8: classname/method
    (let [current_date (new java.util.Date)]
           (.toString current_date))
    ;Thu May 11 16:55:48 COT 2017
    
    ;java current_date.toString()
    (let [current_date (new java.util.Date)]
           (. current_date toString))
    ;Thu May 11 16:56:27 COT 2017
    
    
    ;Java date1.equals(date2)
    (let [date1 (new java.util.Date)
               date2 (new java.util.Date)]
           (.equals date1 date2))
    ;true
    