How do you define a function in another function that can be accessed globally in racket?
The only easy way I know of is to define a binding at the top level that you can later modify inside a function:
Welcome to Racket v6.2.1.
-> (define gf add1)
-> (define (redefine-gf) (set! gf sub1))
-> (gf 1)
2
-> (redefine-gf)
-> (gf 1)
0
Hmm, the question seems rather odd as leeor remarked.
How do you define a function in another function that can be accessed globally in racket?
When the function g is defined inside the function f, which one do you mean should be globally accessible? In case of g that effort is odd. But if you just wanted to ask how to formally define a helper function g inside f that can only be called indirectly by calling f then it would look like this:
(define (f n)
(define (g n)
n)
(g n))
This obviously only outputs the input. But you can't call g itself by name outside of f. You can have as many definitions as you want inside an enclosing function body as long as it's not the last statement in this outer function.
In any case you might wish to take a look:
Racket Guide
Related
((lambda (proc) (proc "yes" "no")) (lambda (a b) a)) ;; yes
((lambda (a b) a) "yes" "no") ;; yes
My question is why are 1 and 2 has the same result and are they the same?
Can someone please elaborate it a bit clearly ?
They give the same result, but they're not "the same". They are two language constructs that happen to give the same result (well, yes, in a functional world, they are equivalent, but I don't think you're refering to that.)
Really, understanding the constructs goes down understanding the language itself (Scheme). I can give you a some hints.
Roughly speaking, the construction (X Y) means "function application". That is, the first X is a function and Y is a parameter, or a set of them. Then the function X is called with the Y parameter(s).
Take your second line, for example, you can see, decomposing it, that it has:
(<Function> "yes" "no")
that is, something that may be a function, then two parameters. In Scheme, you can build anonymous functions, that have no name, but that you specify what do they expect as parameters and what do they do when called. This is called a "lambda function". In your case, the lambda function is defined as:
(lambda (a b) a)
That is, a function without name that accepts two parameters a and b and returns the first one. If you put all together, you get
((lambda (a b) a) "yes" "no")
that clearly it is a function application that returns the first parameter passed, as the lambda function does that.
The first case is similar, but in this case, it is the function itself which is passed as an argument. You have:
(<Function> (lambda (a b) a))
where this Function accepts "something" that can be put to build an application expression and produce a result:
(lambda (proc) (proc "yes" "no"))
that is, accepts some function proc, and "calls" it with two parameters. Note that the function you pass, (lambda (a b) a) accepts two parameters and returns the first, so it produces "yes" again.
I have a simple macro:
(defmacro macrotest [coll]
`(let [result# ~(reduce + coll)]
result#))
Why, if this code works:
(macrotest [1 2 3])
doesn't this code work?
(def mycoll [1 2 3])
(macrotest mycoll)
Symbols are not the same as the value they point to.
One of the important considerations about macros is not just how they create new code, but also how they handle the arguments you pass in.
Consider this:
(def v [1 2 3])
(somefunction v)
The argument v passed to this function does not arrive inside the function as a symbol, v. Instead, because this is a function call, the arguments are evaluated first, then their resulting value is passed into the function. So the function will see [1 2 3].
But macros are not like this, though it is easy to forget. When you call:
(somemacro v)
v is not evaluated and does not pass in [1 2 3]. Inside the macro, all you get is a symbol, v. Now, your macro can emit the symbol you passed in, in the code the macro creates, but it cannot do anything with the value of v unless you add an extra level of evaluation using eval (see footnote -- not recommended).
When you unquote the macro argument, you get a symbol, not a value.
Consider this example:
user> (def a 5)
#'user/a
user> (defmacro m [x] `(+ ~x ~x))
#'user/m
user> (m a)
10
user> (macroexpand '(m a))
(clojure.core/+ a a)
user> (defmacro m [x] `~(+ x x))
#'user/m
user> (m a)
ClassCastException clojure.lang.Symbol cannot be cast to java.lang.Number clojure.lang.Numbers.add (Numbers.java:126)
This would be like trying to do this at the REPL: (+ 'a 'a) Adding symbols, not adding the values those symbols point to.
You might look at these two different definitions of the macro m and think they are doing the same thing. But in the second one, there is an attempt to do something with the symbol x, to do addition with it. In the first macro, the compiler is not asked to do anything with x. It merely is told to emit the addition operation, which will then be actually processed at runtime.
Remember that the point of a macro is to create code not perform runtime activity that a function would do. The code that is created is then immediately run (via implicit eval), so it's easy to forget this separation, but they are two distinct steps.
As a final exercise, pretend you are a compiler. I want you to tell me right now what is the resulting value of this code:
(* t w)
Well? It's impossible. There is no way you can tell me the answer to this question because you have no idea what t and w are. However, later, at runtime, when these presumably have a value, then it will be easy.
And that's what macros do: they output stuff for the runtime to handle.
(Very much not recommended but to help further describe what's happening, this works:)
user> (def a 1)
user> (defmacro m [x] `~(+ (eval x) (eval x)))
user> (m a)
2
In lisp I can bind free variables bound in a closure like this...
(let ((x 1) (y 2) (z 3))
(defun free-variables () (+ x y z)))
(free-variables)
results in ...
6
What I want to know is if it is possible to inspect bound closure variables dynamically?
E.g.
(inspect-closure free-variables)
resulting in something like...
((x 1) (y 2) (z 3))
Thanks SO
Common Lisp
Access to the closure's internal variables is only possible from functions in the same scope (See Jeff's answer). Even those can't query somewhere for these variables. This functionality is not provided by the Common Lisp standard.
Obviously in many cases individual Common Lisp implementations know how to get this information. If you look for example at the SLIME code (a Common Lisp development environment) for GNU Emacs, the code for inspect and backtrace functionalities should provide that. The development wants to show this - for the user/programmer the Common Lisp standard does not provide that information.
You can have multiple functions inside an enclosure, so just add another function
(defun inspect-closure () (list (list 'x x) (list 'y y) (list 'z z)))
and put it inside your let statement
If you're trying to create a function that will access -any- closure then, strictly speaking, I don't think it's possible. x, y, and z are defined locally so if you want to announce them to the world it has to come from within the closure. What you COULD do is build a macro that duplicates let functionality with the added ability to return its local variables. You'll probably want to name it something different, like mylet or whatever.
not sure how to express this..
I've written a macro which takes two arguments. The first one essentially contains identifiers for generating a let expression. The second is the code to use inside the let expression (it wants to have access to these identifiers).
An example:
(match (Add {ast-> x}) (println x))
When the second argument is raw code, things work nicely. x binds to the x defined in the let expression (when macroexpanded it just shows as x). However, when the second argument is a macro which generates (println x), x expands to something like user/x.
Any good ideas on how to fix this?
It sounds like your second macro is defined as:
(defmacro foo
[]
`(println x))
This is incorrect as x will be namespace qualified. The correct version of the second macro in this case would be:
(defmacro foo
[]
`(println ~'x))
Now the x in the println call will be a literal x symbol and not namespace qualified.
This is what Rich Hickey said in one of the blog posts but I don't understand the motivation in using apply. Please help.
A big difference between Clojure and CL is that Clojure is a Lisp-1, so funcall is not needed, and apply is only used to apply a function to a runtime-defined collection of arguments. So, (apply f [i]) can be written (f i).
Also, what does he mean by "Clojure is Lisp-1" and funcall is not needed? I have never programmed in CL.
Thanks
You would use apply, if the number of arguments to pass to the function is not known at compile-time (sorry, don't know Clojure syntax all that well, resorting to Scheme):
(define (call-other-1 func arg) (func arg))
(define (call-other-2 func arg1 arg2) (func arg1 arg2))
As long as the number of arguments is known at compile time, you can pass them directly as is done in the example above. But if the number of arguments is not known at compile-time, you cannot do this (well, you could try something like):
(define (call-other-n func . args)
(case (length args)
((0) (other))
((1) (other (car args)))
((2) (other (car args) (cadr args)))
...))
but that becomes a nightmare soon enough. That's where apply enters the picture:
(define (call-other-n func . args)
(apply other args))
It takes whatever number of arguments are contained in the list given as last argument to it, and calls the function passed as first argument to apply with those values.
The terms Lisp-1 and Lisp-2 refer to whether functions are in the same namespace as variables.
In a Lisp-2 (that is, 2 namespaces), the first item in a form will be evaluated as a function name — even if it's actually the name of a variable with a function value. So if you want to call a variable function, you have to pass the variable to another function.
In a Lisp-1, like Scheme and Clojure, variables that evaluate to functions can go in the initial position, so you don't need to use apply in order to evaluate it as a function.
apply basically unwraps a sequence and applies the function to them as individual arguments.
Here is an example:
(apply + [1 2 3 4 5])
That returns 15. It basically expands to (+ 1 2 3 4 5), instead of (+ [1 2 3 4 5]).
You use apply to convert a function that works on several arguments to one that works on a single sequence of arguments. You can also insert arguments before the sequence. For example, map can work on several sequences. This example (from ClojureDocs) uses map to transpose a matrix.
user=> (apply map vector [[:a :b] [:c :d]])
([:a :c] [:b :d])
The one inserted argument here is vector. So the apply expands to
user=> (map vector [:a :b] [:c :d])
Cute!
PS To return a vector of vectors instead of a sequence of vectors, wrap the whole thing in vec:
user=> (vec (apply map vector [[:a :b] [:c :d]]))
While we're here, vec could be defined as (partial apply vector), though it isn't.
Concerning Lisp-1 and Lisp-2: the 1 and 2 indicate the number of things a name can denote in a given context. In a Lisp-2, you can have two different things (a function and a variable) with the same name. So, wherever either might be valid, you need to decorate your program with something to indicate which you mean. Thankfully, Clojure (or Scheme ...) allows a name to denote just one thing, so no such decorations are necessary.
The usual pattern for apply type operations is to combine a function provided at runtime with a set of arguments, ditto.
I've not done enough with clojure to be able to be confident about the subtleties for that particular language to tell whether the use of apply in that case would be strictly necessary.
Apply is useful with protocols, especially in conjunction with threading macros. I just discovered this. Since you can't use the & macro to expand interface arguments at compile time, you can apply an unpredictably sized vector instead.
So I use this, for instance, as part of an interface between a record holding some metadata about a particular xml file and the file itself.
(query-tree [this forms]
(apply xml-> (text-id-to-tree this) forms)))
text-id-to-tree is another method of this particular record that parses a file into an xml zipper. In another file, I extend the protocol with a particular query that implements query-tree, specifying a chain of commands to be threaded through the xml-> macro:
(tags-with-attrs [this]
(query-tree this [zf/descendants zip/node (fn [node] [(map #(% node) [:tag :attrs])])])
(note: this query by itself will return a lot of "nil" results for tags that don't have
attributes. Filter and reduce for a clean list of unique values).
zf, by the way, refers to clojure.contrib.zip-filter, and zip to clojure.zip. The xml-> macro is from the clojure.contrib.zip-filter.xml library, which I :use