There's been a brief hiatus in my Clojure week. Mostly due to me being knackered after some hardcore work days. In the last instalment I got my basic VimClojure environment set up. After that particular mission Day One’s excercises seemed almost trivial. I expect things to become more difficult in the next couple of sessions of course.
bigstr.clj
Implement a function called (big st n) that returns true if a string st is longer that n characters.
Believe it or not I did this the old skool way whilst I was in St Ann’s café, up in the Malvern hills. That’s right, on a bit of paper. I was rather smug when I typed it in and it worked first time, trivial though it is.(defn big [st n] (< n (count st)))
Brill, the Lisp syntax does what you would expect if you’ve ever had a crack at writing any Lisp code.Clojure
user=> (big "charlie" 3)
true
user=> (big "charlie" 8)
false
user=>
collection-type.clj
Write a function called (collection-type col) that returns :list, :map, or :vector based on the type of collection col.
This one I didn’t do on paper. But it did teach me how to use cond. I added a test for unknown collections. If the people using my code are anything like me they will probably call it with the wrong type at some point. Returning :unknown_type seems polite as well as practical. Perhaps the correct way would be to throw some sort of an exception. I guess I shall find that out in the next couple of sessions.(defn collection-type [col]
( cond
(map? col) :map
(list? col) :list
(vector? col) :vector
:else :unknown_collection_type
)
)
Just some quick tests to verify that the function works as expected.Clojure
user=> (collection-type {:a "review", :b "blog", :c "current news", :d "diary"})
:map
user=> (collection-type '("review","blog","current news","diary"))
:list
user=> (collection-type ["review" "blog" "current news" "diary"])
:vector
user=> (collection-type "earwig")
:unknown_collection_type
user=>
First impressions of Clojure
Clojure seems like a reasonably well implemented Lisp. I have always struggled with the profusion of brackets in dear old Lisp, but otherwise its rather nice to write. I must confess that the VimClojure setup was a bit of a challenge, but now its done, developing programs is a breeze. I’m pretty undecided on Clojure so far — I guess I need to write something non-trivial to get a sense of how it feels to use it. Of which more in the next installment.