I’ve been working my way through the Clojure section for “Seven Languages in Seven Weeks” by Bruce Tate. This book, so far, has been awesome. Read the first section under Clojure, and it’s been an easy read. I love all the Star Wars references that he makes throughout the section, and I forsee it continuing. It starts at the beginning where he’s saying that writing Clojure statments is similar to the way Yoda talks, and then he jumps right into examples. Entertaining, catchy, kinda funny. It’s good stuff.
At the end of the section, he’s provided a few assignments of what to at the end of the “first day.” I didn’t do them in order, so I won’t post them in order.
The first was to write a function (big str n) that takes a string and a number as input and returns true if the string’s length is bigger than the number. The answer:
(defn big [str n] (> (count str) n))
Function explicit function definitions are organized as (defn functionName [params] body). The “Yoda-talk” that the author talks about is clearly demonstrated in the body of the function above. Yoda speaks like “Verb phrase – noun + helping verb” i.e. “understand me later, you will.” Clojure’s equivalent of verbs are operators (i.e. >, <, +, =), with the operands (or nouns) coming after.
Next problem: write a function (collection_type col) that returns :list, :map, or :vector, depending upon the type for col
Answer:
(defn collection_type [col]
(if (instance? clojure.lang.PersistentArrayMap col)
:map
(if (instance? clojure.lang.PersistentList col)
:list
(if (instance? clojure.lang.PersistentVector col)
:vector))))
Action shot:
Maps (in {} ), lists (in [] ), and vectors (in () ) are three different data types in Clojure. I’m still having difficulty understanding the difference between lists and vectors, other than the () for lists and the [] that denote them. It’s good that they have a syntax structure that separates them, but why is one useful over the other? Maybe I’ll learn here in time as I continue to read. We’ll see.
It’s an interesting read, and interesting to figure out exactly how nested if’s work. Gotta keep going!!
I’m also interested in trying to do a post that uses clojure on this page! Trying to get info via StackOverflow, found a post that might help out so I can give it a shot: http://stackoverflow.com/questions/167262/how-do-you-make-a-web-application-in-clojure
Maybe one of these APIs can make it happen! We’ll have to see what we can do.
(defn whatIDidToday [time]
(if (< time 7AM)
(sleep Patrick)
(if (< time 12PM)
(homework Patrick)
(if(< time 5PM)
(drive Patrick)
(if(< time 7PM)
(clojure Patrick)
(caffiene_high)))))
Quite the day.
Add a comment