0
votes

I'm trying to read a file in a macro in Clojure.

I'm launching my macro with that line :

(def result (rd [s (FileReader. (File. "myFile.txt"))] (.read s)))

where "rd" is the name of my macro.

The prototype of my macro is like that :

(defmacro rd
  ([] nil)
  ([arg] arg)
  ([[variable val] expr]
  )
)

The thing is that I can "execute" the FileReader, but when I'm trying to "execute" expr (.read s), it's not working because s is not known.

So I'm trying to link my elements of a vector to made s known, so I want "variable" pointed by val.

I'm not sure I'm in what I want to do, so if you see other ways, I'm up to it.

Thanks in advance guys.

1
Why do you want to write a macro and not a function? - Shlomi
Because using a macro is mandatory, I know that using a function would be faster but I have to use macro - ElMacx
Why is it mandatory? is it for school? Macros are most commonly used to provide custom "syntax". Keep in mind that they are evaluated at compile time. Do you need the file to be read at compiled time? I am not clear on what exactly you need to accomplish. - Shlomi
Could you include one more example of calling the macro and what the output should be? - Arthur Ulfeldt
Yeah it's for my school, I'm blocked on that subjet for now 4 days and can't find a solution. No the file needs to be read on the execution on the command line : (def result (rd [s (FileReader. (File. "myFile.txt"))] (.read s))). And I don't have any other examples, this is the only one I have sorry - ElMacx

1 Answers

1
votes

if you need to read the file at runtime, as you said, you need to introduce the var.. something like this:

(defmacro rd [[variable val] expr]
  `(let [~variable ~val]
     ~expr))

and then your macro call would expand to this:

(let [s (FileReader. (File. "myFile.txt"))] (.read s))