Here's a way to do it.  Not sure if this is what you want.

(let [x (atom 12)]
  (defn next-number [] (swap! x inc)))

Functions are clojures, which means that next-number can retain a pointer 
to a variable that it can see when it's defined.

If some of the ideas here are unfamiliar:
The atom function gives you something that you can modify in place, in 
effect, and swap! is one way to modify it.  Passing inc to swap! applies 
inc to the value in the atom x, and stores the result back into the atom.  
(I'm not sure if my wording here is precisely correct, but the idea should 
be clear enough.)

You can also use a top-level variable instead of a local one defined by let:

(def x (atom 12))
(defn next-number [] (swap! x inc))
@x ;=> 12
; [the @ operator gets the value out of the atom.]
(next-number) ;=> 13
@x ;=> 13
(next-number) ;=> 14

With the let form, (next-number) is your *only* way of accessing x, which 
could be a good thing or a bad thing--unless you define other functions in 
the scope of the let at the same time that you define next-number:

(let [x (atom 12)]
  (defn next-number [] (swap! x inc))
  (defn undo-next [] (swap! x dec))
  (defn check-number [] @x))

(check-number) ;=> 12
(check-number) ;=> 12
(next-number)    ;=> 13
(check-number) ;=> 13
(undo-next)        ;=> 12
(check-number) ;=> 12


(Perhaps many Clojure programmers *would* consider all of this perverse, 
but similar things are considered ... cool in the some corners of the 
Scheme and Common Lisp worlds.  ("cool" doesn't necessarily mean "useful 
often"--just *cool*--and maybe useful now and then.))

On Friday, June 13, 2014 7:16:09 PM UTC-5, Christopher Howard wrote:
>
> This might be kind of perverse, but I was wondering if it was possible 
> to write a function or macro that takes "hidden parameters", i.e., 
> uses symbols defined in the scope of use, without passing them in 
> explicitly. 
>
> For example, function "next-number" takes hidden parameter "x", so 
>
> => (let [x 12] (next-number)) 
>
> Would return 13. 
>
> With the whole "code is data" paradigm it seems like this should be 
> possible, but I haven't figured out how to do this yet without getting 
> an error. 
>

-- 
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