defn within defn

219 views
Skip to first unread message

Hozumi

unread,
Feb 10, 2010, 4:28:44 PM2/10/10
to Clojure
Hi all.
Is it not recommended to use defn within defn?

Normal function is faster than the function which has inner function
which actually doesn't run.
------------------------------------------------------------------------------
(defn aaa1 []
(defn bbb [] 1)
1)

(defn aaa2 [] 1)

user> (time (dotimes [_ 10000000] (aaa1)))
"Elapsed time: 4083.291 msecs"
nil
user> (time (dotimes [_ 10000000] (aaa2)))
"Elapsed time: 58.34 msecs"
nil
------------------------------------------------------------------------------
In scheme's case both code have been excuted in the same time.

None of clojure code I have seen have inner function.
I like inner function because it doesn't consume a name from namespace
and make it clear that inner function is only used by outer function.
Thanks.

.Bill Smith

unread,
Feb 10, 2010, 5:58:40 PM2/10/10
to Clojure
Hozumi, nested defn's are definitely not recommended. I suggest using
letfn for the inner function.

Bill Smith
Austin, TX

Kevin Downey

unread,
Feb 10, 2010, 6:01:05 PM2/10/10
to clo...@googlegroups.com
scheme's define is scoped inside a function. clojure is not scheme.
clojure's def (which defn uses) is not lexical or scoped in anyway, it
always operates on global names. if you want lexical scope please use
one of clojure's lexical scoping constructs, let or letfn.

> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clo...@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+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en

--
And what is good, Phaedrus,
And what is not good—
Need we ask anyone to tell us these things?

Hozumi

unread,
Feb 10, 2010, 6:51:47 PM2/10/10
to Clojure
Hi, Bill.
oh, letfn is what I wanted ! Thank you.
Sorry, I missed preview disqussion.
letfn - mutually recursive local functions
http://groups.google.com/group/clojure/browse_thread/thread/a7aad1d5b94db748

letfn is pretty good.
---------------------------------------------------------------------------
(defn aaa1 []
(letfn [(bbb [] 1)]
1))

user> (time (dotimes [_ 10000000] (aaa1)))

"Elapsed time: 100.981 msecs"
nil
---------------------------------------------------------------------------

Hi Kevin.
I have understood that def is not lexical scoped.


---------------------------------------------------------------------------
(defn aaa1 []
(defn bbb [] 1)
1)

user> (aaa)
1
user> bbb
#<user$aaa1__2324$bbb__2326 user$aaa1__2324$bbb__2326@55eef3c1>
---------------------------------------------------------------------------
Thank you!

Reply all
Reply to author
Forward
0 new messages