2015-02-14 20:23 GMT+01:00 Steve Miner <stevemi...@gmail.com>:

> Clojure doesn't give you direct access to the name of the function you're
> defining.  However, you could use a macro to get that.  Here’s one way.
> This macro binds the strange symbol %0 to  the symbol naming the current
> function.
>
> ;; %0 is bound to the function's symbolic name within the function.
> Useful for pre-conditions,
> ;; logging and error reporting.
> (defmacro defn0 [fname & fdcls]
>   `(let [~'%0 (symbol (name (ns-name *ns*)) (name '~fname))]
>      (defn ~fname ~@fdcls)))
>
> ;; For example...
> (defn0 my-func [x]
>   (println "calling" %0 x)
>   (+ x 3))
>
> user=> (my-func 11)
> calling user/my-func 11
> 14
>
> The downside to using something like this is that other people might have
> a harder time reading your code.  I thought it was clever when I wrote it,
> but I don't actually use it much.
>

​Very handy. Another place where I can use it to write a general function
to check parameters. When I have several functions that use almost the same
parameters I could write a generic function to check them (DRY) and give
the function name to handle the differences.
​

​I rewrote it a little to make it more clear:
    (defmacro defn-with-functionname [fname & fdcls]
      `(let [~'%FUNCNAME (symbol (name (ns-name *ns*)) (name '~fname))]
         (defn ~fname ~@fdcls)))

    (defn-with-functionname my-func [x]
      (println "calling" %FUNCNAME x)
      (+ x 3))
​


>
>
> > On Feb 14, 2015, at 11:11 AM, Cecil Westerhof <cldwester...@gmail.com>
> wrote:
> >
> > In Bash I use the following construct:
> >     printf "${FUNCNAME} needs an expression\n"
> >
> > In this way I do not have to change the print statement when the name of
> the function changes. Is something like this also possible in clojure?
>

-- 
Cecil Westerhof

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to