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.concat("</p>")
text = sanitize(text) unless options[:sanitize] == false
text
end
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 naivite (sorry, couldn't get the French characters to display in xml) 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.
Posted: 21 February 2012