Dirk Bergmann

Developer, panographer. Does consultancy work from own company. Lives in Chiang Mai, Thailand.


Chiang Mai

Hua Hin

Thailand Hotels

ListVote - List. Vote. Learn.

Partnerseek - Find Partners

Naïveté to Brilliance

Unlike Scala, even beginning learners of Clojure will experience the fun of functional programming almost immediately. 

Converting the Rails function ?simple_format? from Ruby

def simple_format(text, html_options={}, options={})
 text = text ? text.to_str : ''
 text = text.dup if text.frozen?
 start_tag = tag('p', html_options, true)
 text.gsub!(/\r\n?/, "\n")
 text.gsub!(/\n\n+/, "</p>\n\n#{start_tag}")
 text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') 
 text.insert 0, start_tag
 text = sanitize(text) unless options[:sanitize] == false

to Clojure (leaving out options)

(defn simple-format [text]
(let [patterns
 {#"\r\n?" "\n"  #"\n\n+" "</p>\n\n<p>" #"([^\n]\n)(?=[^\n])" (str #"$1"  "<br />")}]
(str "<p>" (reduce #(clojure.string/replace %1  (key %2) (val %2)) text
patterns) "</p>")))

illustrates the fundamental naïveté of imperative programming with its silly reassignments, incidental state and mutability. It's laughing at this and marvelling at the sheer brilliance of Clojure in equal measure that make Clojure so much fun.