Feb 21
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”) # \r\n and \r -> \n
text.gsub!(/\n\n+/, “</p>\n\n#{start_tag}”) # 2+ newline -> paragraph
text.gsub!(/([^\n]\n)(?=[^\n])/, ‘\1<br />’) # 1 newline -> 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 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.
Recent Comments