# Professional Clojure

## Chapter 1 - Have a Beginner's Mind

In computer science, imperative programming is a programming paradigm that uses statements that change a program's state.

Value Oriented

Clojure promotes a style of programming commonly called "value-oriented programming."

``````(defn fib [n]
(cond
(= n 0) 0
(= n 1) 1
:else (+ (fib (- n 1))
(fib (- n 2)))))
``````

You can rewrite a function to leverage memorization to see a signicant improvement in the execution time:

``````(def memoized-fib
(memoize (fn [n]
(cond
(= n 0) 0
(= n 1) 1
:else (+ (fib (- n 1))
(fib (- n 2)))))))
``````

Thinking Recursively

A naive recursive defnition of a factorial in Clojure may look like the following:

``````(defn factorial [n]
(if (= n 1)
1
(* n (factorial (- n 1)))))
``````

tail recursive style (using `recur`):

``````(defn factorial2 [n]
(loop [count n acc 1]
(if (zero? count)
acc
(recur (dec count) (* acc count)))))
``````

`trampoline` and `letfn`:

``````(defn my-even? [n]
(letfn [(e? [n]
(if (= n 0)
true
#(o? (dec n))))
(o? [n]
(if (= n 0)
false
#(e? (dec n))))]
(trampoline e? n)))

(defn my-odd? [n]
(not (my-even? n)))
``````

higher order functions

``````(defn wrapInTransaction [f]
(do
(startTransaction)
(f)
(completeTransaction)))

(wrapInTransaction #(
(do
{"ft_lang_label":"__label__en","ft_lang_prob":0.59259766,"math_prob":0.9923514,"size":1529,"snap":"2023-40-2023-50","text_gpt3_token_len":457,"char_repetition_ratio":0.12655738,"word_repetition_ratio":0.14671814,"special_character_ratio":0.32243297,"punctuation_ratio":0.070866145,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9987784,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-09-26T11:34:08Z\",\"WARC-Record-ID\":\"<urn:uuid:894660dc-6e05-4f82-b215-98c8780fd334>\",\"Content-Length\":\"5896\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:dd0192b6-f6f1-41dd-b523-09394a6887da>\",\"WARC-Concurrent-To\":\"<urn:uuid:0f246c2e-bd49-4047-b081-450c7b4e00de>\",\"WARC-IP-Address\":\"45.77.44.74\",\"WARC-Target-URI\":\"https://jchk.net/read/professional-clojure\",\"WARC-Payload-Digest\":\"sha1:CSOTN4JQYWE4LQMRVQUYQZWNTMIUMQX4\",\"WARC-Block-Digest\":\"sha1:DO5WS6DF4KBUHCPAMGRH6ZVMMI65EZZY\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-40/CC-MAIN-2023-40_segments_1695233510208.72_warc_CC-MAIN-20230926111439-20230926141439-00131.warc.gz\"}"}