Clojure + Clojurescript:宏读取当前文件的代码 [英] Clojure + Clojurescript: Macro to read code of current file

查看:251
本文介绍了Clojure + Clojurescript:宏读取当前文件的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(defmacro magic []
  (slurp *file*))

这在clojure中可以正常工作,但不能在clojurescript中使用(至少不使用lein figwheel)。

This works fine in clojure, but not in clojurescript (atleast not with lein figwheel).

我需要以下工作在Clojure和Clojurescript。我认为宏是正确的解决方案,但我对其他技术开放。

I need the following to work in both Clojure and Clojurescript. I think a macro is the right solution, but I'm open to other techniques.

我想要一种方式读取当前文件一个字符串。例如:

I want a way to read the current file as a string. For example,

(ns my-test
  (:require blah))

(def foo 20)

(println (blah/magic))

这应该会导致(打印输出)

this should then result in (being printed out)

(ns my-test
  (:require blah))

(def foo 20)

(println (blah/magic))

如果我只需要在Clojure工作,我可以做有趣的事情与当前文件,并在运行时读取它。但是,我需要这也工作在Clojurescript(我不想设置一些REST API提供* .cljs文件) - 因此,有一些方法在编译时通过一些宏?

If I only needed this to work in Clojure, I could do funny things with the current file and reading it at run time. However, I need this also to work in Clojurescript (and I don't want to setup some REST API to serve *.cljs files) -- thus, is there some way to do this at compile time via some macro?

假设你想写一个cheating quine,你会怎么做?可能是像(println(slurp * file *))。现在,有什么问题?

Suppose you wanted to write a "cheating quine" -- how would you do it? Probably something like (println (slurp *file*)). Now, what's the problem? This doesn't work in clojurescript when running under lein figwheel.

推荐答案

您需要阅读条件,如下:

You need Reader Conditionals like this:

(defn build-list []
  (list #?@(:clj  [5 6 7 8]
            :cljs [1 2 3 4])))

请参阅此处的文档:

http://clojure.org/guides/reader_conditionals

https://github.com/clojure / clojurescript / wiki / Using-cljc

UPDATE 1

如果要修改当前执行的源代码,您可以始终构造一个字符串并使用 eval

If you want to modify the currently executing source code, you can always construct a string and use eval:

(eval (read-string "(defn darth [] (println \"I have the ultimate power now...\" ))" ))

(darth)
;=> I have the ultimate power now...

但是,由于ClojureScript是编译的,我不认为

However, since ClojureScript is compiled, I don't think there is any simple way of finding the source original source code, if that's what you're after.

UPDATE 2

这是一个有趣的问题。最近我来的是这样的:

It's an interesting problem. The closest I've come so are is something like this:

(ns clj.core)

(defmacro fred [& forms]
  (doseq [f forms]
    (println `~f)))

(fred 
  (+ 1 2)
  (* 2 3)
)

(defn -main [& args])

结果:

> lein run    
(+ 1 2)
(* 2 3)

这篇关于Clojure + Clojurescript:宏读取当前文件的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆