Can I refer another namespace and expose its functions as public for the current ns?

前端 未结 3 1784
傲寒
傲寒 2021-02-01 20:37

I thought use would do it but it seems the mapping created in the current namespace is not public. Here is an example of what I\'d like to achieve:

         


        
相关标签:
3条回答
  • 2021-02-01 21:17

    Does this help?

    (defmacro pull [ns vlist]
      `(do ~@(for [i vlist]
               `(def ~i ~(symbol (str ns "/" i))))))
    

    Here's an example:

    (ns my-ns)
    
    (defmacro pull [ns vlist]
      `(do ~@(for [i vlist]
               `(def ~i ~(symbol (str ns "/" i))))))
    
    (pull clojure.string (reverse replace))
    
    (defn my-reverse
      []
      (reverse "abc"))
    
    (ns my-ns-2)
    
    (defn my-fct-2 []
      (list (my-ns/my-reverse)
            (my-ns/reverse "abc")))
    
    (my-fct-2)
    

    If you want to just pull in everything, then:

    (defmacro pullall [ns]
      `(do ~@(for [i (map first (ns-publics ns))]
               `(def ~i ~(symbol (str ns "/" i))))))
    
    (pullall clojure.string)
    
    0 讨论(0)
  • 2021-02-01 21:27

    One way to do this selectively (specifying each function explicitly) is to use something like Zach Tellman's Potemkin library. An example of it's use is found in the lamina.core namespace which serves as the public entry point for Lamina, importing the key public functions from all other internal namespaces.

    You can also use clojure.contrib.def/defalias:

    (use 'clojure.contrib.def/defalias)
    (defalias foo clojure.string/blank?)
    (foo "")
    
    0 讨论(0)
  • 2021-02-01 21:28

    To pull everything from namespace that may have macros defined within use this

    (defmacro pullall [ns]
      `(do ~@(for [[sym var] (ns-publics ns)]
               `(def ~sym ~var))))
    
    0 讨论(0)
提交回复
热议问题