In clojure how can I test if a a symbol has been defined?

前端 未结 3 1194
无人及你
无人及你 2021-01-17 07:55

I would like to see if a symbol has been \"def\" ed, but I can\'t see any ifdef syntax

相关标签:
3条回答
  • 2021-01-17 08:22
    user> (resolve 'foo)
    nil
    user> (def foo 3)
    #'user/foo
    user> (resolve 'foo)
    #'user/foo
    
    0 讨论(0)
  • 2021-01-17 08:28

    Can use find-var for this

    (bound? (find-var 'user/y))
    
    0 讨论(0)
  • 2021-01-17 08:33

    resolve or ns-resolve may do what you're looking for:

    user> (def a 1)
    #'user/a
    user> (def b)
    #'user/b
    user> (resolve 'a)
    #'user/a
    user> (resolve 'b)
    #'user/b
    user> (resolve 'c)
    nil
    

    To get a boolean:

    user> (boolean (resolve 'b))
    true
    

    EDIT: per MayDaniel's comment, this isn't exactly what you asked for, but it will get you there. Here's an implementation of bounded? (probably not the best name):

    (defn bounded? [sym]
      (if-let [v (resolve sym)]
        (bound? v)
        false))
    
    user> (map bounded? ['a 'b 'c])
    (true false false)
    
    0 讨论(0)
提交回复
热议问题