I am trying to implement pattern-matching in Clojure. My preference is to use core.match to match on a given regex pattern. I tried this:
(defn markdown->html [markdown-line]
(match [markdown-line]
[(boolean (re-matches #"#\s+\w+" markdown-line))] (str "<h1>")))
This does not even compile properly. I pivoted to a case conditional:
(defn markdown->html [markdown-line]
(case markdown-line
(boolean (re-matches #"#\s+\w+" markdown-line)) (str "<h1>")))
However, that did not give me the expected results when I invoke it with this: (markdown->html "# Foo")
However, this works!
(defn markdown->html [markdown-line]
(if
(boolean (re-matches #"#\s+\w+" markdown-line)) (str "<h1>")))
For all the tests above, I am invoking the function like so: (markdown->html "# Foo")
Does anyone know what I am doing wrong?
See the docs for
case:For example:
And
clojure.core.match/matchis similar, so I'd say both are wrong tool for your problem.If you're trying to write function for converting Github markdown to HTML, check
clojure.string/replace, which can help you:Or even better, using
$for group:By the way, your example can be improved like this:
Ifis missing else branch, sowhenis better; you don't have to useboolean, becausefalseornilare considered as logical false and any other value is logical true and there is no reason to wrap one string instr.EDIT: Function for headers
<h1>-<h6>: