Overthunk

Ch 6 + 0.5 of Ch 7 of Brave Clojure

Jul 10, 2020


Contents

Pascal’s Triangles

In mathematics, Pascal’s triangle is a triangular array of the binomial coefficients.

For example -

    [1]
   [1 1]
  [1 2 1]
 [1 3 3 1]
[1 4 6 4 1]

The 4Clojure problem asks you to create a function which returns the nth row of Pascal’s Triangle. I tried solving it before with map and reduce but it didn’t work out.

Today, I decided to give the problem another shot. And lo and behold, a solution came to me in about 5 minutes.

(defn pascalize
  ([n] (pascalize (dec n) '(1)))
  ([n p]
   (if (zero? n)
     p
     (recur (dec n) (conj (map #(apply + %)  (partition-all 2 1 p)) 1)))))

Dead simple. I think this was the first time I instinctively reached for a loop recur construct to solve a problem.

Chapter 6

map and inc are symbols

When you give clojure a symbol like map, it finds the corresponding var in the current namespace, gets a shelf address, and retrieves an object from that shelf for you.

if you want to use the symbol itself, quote it

'inc
=> inc

'(map inc [1 2 3])
=> (map inc [1 2 3])

(def great-books ["Sherlock Holmes" "Alice in Wonderland"])
=> #'clojure-noob.ch6/great-books

great-books
=> ["Sherlock Holmes" "Alice in Wonderland"]

Interning a var

(get (ns-interns *ns*) 'great-books)
#'clojure-noob.ch6/great-books -> reader form of a var

;; use #' to grab ahold of the var corresponding to the symbol

(deref #'clojure-noob.ch6/great-books)
;; => ["Sherlock Holmes" "Alice in Wonderland"]

(def great-books ["The power of bees" "Journey to Upstairs"])

great-books
;; => ["The power of bees" "Journey to Upstairs"]
(create-ns 'cheese.taxonomy)
=> #namespace[cheese.taxonomy]

You can use the returned namespace as an argument in a function call

(ns-name (create-ns 'cheese.taxonomy))
=> cheese.taxonomy

Project Organization

ns macro allows you to incorporate require, use, in-ns alias and refer ns refers the clojure.core namespace by default

(ns the-divine-cheese-code.core
  (:refer-clojure :exclude [println]))

Chapter 7

Clojure Evaluation model -

Homoiconic -> reason about the code as a set of data structures that you can manipulate programmatically.

Takeaways

Coming back to problems after a while is good and can yield productive results. I also need to revisit old functions and what I’ve learned previously to keep the knowledge fresh in my mind.

Today’s tally -