1

I'm trying to create a macro that accepts 2 strings, 1 would be a regex pattern and the other a string to test it on. From some reading (including around here) and seeing as #"" is a reader macro I tried doing it using re-pattern but it seems to fail at runtime with:

Exception in thread "main" java.lang.ClassCastException: clojure.lang.Symbol cannot be cast to java.lang.CharSequence

My code:

(defmacro checkre [ strre strstring ] 
  (re-find (re-pattern strre) strstring))

Example call:

(defn hasthing [xp]
  (checkre "(?i)^.*blabla" xp))

Thanks!

2 Answers 2

4

You are close; but you don't need (and probably shouldn't use) a macro for this:

(defn checkre [ strre strstring ] 
  (re-find (re-pattern strre) strstring))
(defn hasthing [xp]
  (checkre "(?i)^.*blabla" xp))
(hasthing "stuff blabla")
;=> "stuff blabla"

Macros are best used only when needed, because they don't compose as easily as functions and are harder to reason about (because of the macro expansion phase).

The reason your macro version fails is that it is trying to bind strre and strstring at macro expansion time, when they are symbols, rather than strings. A (slightly perverted) macro version which works is:

(defmacro checkre [ strre strstring ] 
  `(re-find ~(re-pattern strre) ~strstring))
(defn hasthing [xp]
  (checkre "(?i)^.*blabla" xp))
(hasthing "stuff blabla")
;=> "stuff blabla"
Sign up to request clarification or add additional context in comments.

Comments

1

Why would you make this a macro ? Just make it a function and it will work fine.

=> (defn checkre 
     [strre strstring] 
     (re-find (re-pattern strre) strstring))
#'user/checkre
=> (checkre "[aeiou]" "Hello")
"e"

If you want to create a function that binds the regexp, let your function return a function

=> (defn checkre 
     [strre] 
     (fn [strstring] (re-find (re-pattern strre) strstring)))
=> (def hasthing (checkre "[aeiou]"))
=> (hasthing "Hello")
"e"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.