I want to create a function that receives 2 arguments and returns a function that receives himself a board. That function needs to check user input and make changes in the board according to the input. I have no problems with the user input and the changes i have to do to the board. My problem is with the function that returns a function. To do that i'm using a lambda. This is the code i'm working on:
(defun faz-jogador-manual (n_aneis peca)
#'(lambda (tabuleiro)
(setf jogada (le-posicao))
(let ((num_anel (first jogada))
(posicao_anel (second jogada))
(tab (copia-tabuleiro tabuleiro)))
(tabuleiro-poe-peca tab peca num_anel posicao_anel))))
This function should return a function lambda, but when i call the function using:
(faz-jogador-manual 3 'X)
i get the following:
#<Closure (:INTERNAL FAZ-JOGADOR-MANUAL 0) [X] # #x2112f462>
I don't know what i'm doing wrong, is it the call? is the function per se? I need help with this one.
Common Lisp is a Lisp-2, which means that it has a separate namespace for functions and values; as a result, functions need to be treated slightly specially in this case. (This is in contrast to most Lisps.)
When you return a function as a value, you can't just invoke it in the same way as if you had defined it with defun. You need to use funcall or apply to do so. You can do it like this:
;; insert an appropriate argument in place of tabuleiro for the inner function
(funcall (faz-jogador-manual 3 'X) tabuleiro)
If you want to understand this behavior in more detail, you can probably find lots of references online, like this one.
Closure object is a lambda with lexical variables captured from the context (n_aneis and peca in your case). It's a value you can put into a variable or apply as a function with funcall.
(defvar closure (faz-jogador-manual 3 'X))
(funcall closure *table*)
Related
In specified conditions I want to print name of fuction in this function. but I don't know how to get it.
In C++ I can use preprocessor macro __FUNCTION__. I something simmilar in AutoLISP?
This is definitely possible. Let's look at two situations:
1) You're writing the function.
This should be easy, just define a variable that has the same name as the function and you're good to go. (As discussed in the comments above.)
You could even use something more descriptive than the actual name of the function. (defun af () ...) could be called "Awesome Function" instead of "af".
I would also recommend using standard constant value formatting: Capital letters with underscores to separate words. (setq FUNCTION_NAME "AwesomeFunction"). (This is just like PI which is set for you and you shouldn't change it - it's a constant.)
2) You're calling a function that you might not know the name of until the code runs.
Some examples of this:
(apply someFunctionInThisVariable '(1 2 3))
(mapcar 'printTheNameOfAFunction '(+ setq 1+ foreach lambda))
(eval 'anotherFunctionInAVariable)
To print the name of a function stored in a variable - like this (setq function 'myFunction) - you need to use the (vl-princ-to-string) function.
(vl-princ-to-string function) ;; Returns "MYFUNCTION"
(strcase (vl-princ-to-string function) T) ;; Returns "myfunction"
(princ
(strcase
(vl-princ-to-string function)
T
)
) ;; Command line reads: myfunction
The (vl-princ-to-string) function can be used on any type that can be printed and will always return a string. It's great if you don't know whether you have a number or a word, etc.
Hope that helps!
P.S. I first used this technique when I was writing a testing function. Send it a function and an expected value and it would test to see if it worked as expected - including printing the function's name out as part of a string. Very useful if you have the time to setup the tests.
I want to define a list of accumulators with Emacs Lisp and write the following code, but I got a error saying that initV is a void variable. It seems initV is not evaluated in the function define-accum. Where is I make a mistake? (I just want to know why although I know there is other ways to reach my target.)
(defun define-accum (name initV)
(defalias name (lambda (v) (+ v initV))))
(setq accums '((myadd1 . 1)
(myadd2 . 2)))
(dolist (a accums)
(define-accum (car a) (cdr a)))
(message "result = %d" (+ (myadd1 1) (myadd2 1)))
You need to use backquotes properly. This would work for you, for instance:
(defun define-accum (name initV)
(defalias name `(lambda (v) (+ v ,initV))))
See here for an explanation
Apart from using backquotes, you can activate lexical binding (if you're using Emacs 24 or newer). For example, if I put your code in a .el file and put this on the first line:
;; -*- lexical-binding: t -*-
then I get the output:
result = 5
This works because the lambda function in define-accum will reference the initV in the environment where it's being defined (thus picking the variable in the argument list), and create a closure over this variable. With dynamic binding (the default), the function would look for initV in the environment where it's being called.
To add a little to what others have said -
If the variable (initV) is never actually used as a variable, so that in fact its value at the time the accumulator is defined is all that is needed, then there is no need for the lexical closure that encapsulates that variable and its value. In that case, the approach described by #juanleon is sufficient: it uses only the value at definition time - the variable does not exist when the function is invoked (as you discovered).
On the other hand, the lexical-closure approach lets the function be byte-compiled. In the backquote approach, the function is simply represented at runtime by a list that represents a lambda form. If the lambda form represents costly code then it can make sense to use the lexical-closure approach, even though (in this case) the variable is not really needed (as a variable).
But you can always explicitly byte-compile the function (e.g. ##NAME## in your define-accum. That will take care of the inefficiency mentioned in #2, above.
Why do we have to use funcall to call higher order functions in Common Lisp? For example, why do we have to use:
(defun foo (test-func args)
(funcall test-func args))
instead of the simpler:
(defun bar (test-func args)
(test-func args))
Coming from a procedural background, I'm a bit surprised by that since the languages I'm more used to (e.g. Python, C#) don't need the distinction. In particular, on the source level at least, the C# compiler transforms it to something like func.invoke().
The only problem I see is that this would mean we couldn't call a global function test-func anymore because it'd be shadowed, but that's hardly a problem.
Strictly speaking, funcall would not be needed, but there are some lisps (lisp-2 variants, such as Common Lisp) that separate the variable name space of the function name space. Lisp-1 variants (e.g. Scheme) do not make this distinction.
More specifically, in your case, test-func is in the variable name space.
(defun foo (test-func args)
(funcall test-func args))
Therefore you need a construct that actually searches the function object associated with this variable in the variable name space. In Common Lisp this construct is funcall.
See also this answer.
The majority of Lisps have two namespaces (functions and variables). A name is looked up in the function namespace when it appears as the first element in an S-expression, and in the variable namespace otherwise. This allows you to name your variables without worrying about whether they shadow functions: so you can name your variable list instead of having to mangle it into lst.
However, this means that when you store a function in a variable, you can't call it normally:
(setq list #'+) ; updates list in the variable namespace
(list 1 2 3) => (1 2 3) ; looks up list in the function namespace
Hence the need for funcall and apply:
(funcall list 1 2 3) => 6 ; looks up list in the variable namespace
(Not all Lisps have two namespaces: Scheme is an example of a Lisp with just one namespace.)
In Common Lisp, each symbol can be associated with its symbol-function and its symbol-value, among other things. When reading a list, by default, Common Lisp interprets:
arg1 as a function and so retrieves test-func's symbol-function, which is undefined -- thus function bar doesn't work
arg2 as something to be evaled -- thus function foo retrieves test-func's symbol-value, which, in your case, happens to be a function
I'm trying to pass a function as an argument and call that function within another function.
A piece of my code looks like this:
(defun getmove(strategy player board printflag)
(setq move (funcall strategy player board))
(if printflag
(printboard board))
strategy is passed as a symbol represented in a two dimensional list as something such as 'randomstrategy
I keep getting the error:
"FUNCALL: 'RANDOMSTRATEGY is not a function name; try using a symbol instead...
When I replace strategy with 'randomstrategy it works fine.
I can also call randomstrategy independently.
What is the problem?
The problem is that the variable strategy does not contain the symbol randomstrategy but rather the list (!) 'randomstrategy (which is a shorthand notation for (quote randomstrategy)).
Now, you could, of course, extract the symbol from the list by way of the function second, but that would only cover the real problem up, which is probably somewhere up the call chain. Try to determine why the argument that is passed to function getmove is 'randomstrategy, not randomstrategy as it should be. (Maybe you erroneously used a quote inside of a quoted list?)
Oh, and don't let yourself be confused by the fact that (funcall 'randomstrategy ...) works: the expression 'randomstrategy does not, after all, evaluate to itself, but to the symbol randomstrategy.
Is strategy a variable with a functional value? If not, then use the #' syntax macro before it, i.e. #'strategy, or just (if the function is global) 'strategy.
WHY? Because arguments of a funcall call are evaluated. And your strategy symbol is just a variable name in this case. Variable this value 'RANDOMSTRATEGY. But you should give to funcall a function. How to access function if we have a symbol?
Three cases:
Symbol may denote a variable with functional value.
Symbol may denote a global function (symbol-function is the accessor in this case.
Symbol may denote a local function (flet, labels and so on).
It looks like you forgot to define RANDOMSTRATEGY function.
(defun RANDOMSTRATEGY …)
Hmm
FUNCALL: 'RANDOMSTRATEGY
Maybe you have (setq strategy ''RANDOMSTRATEGY)?
Then strategy will evaluate to 'RANDOMSTRATEGY.
Did you notice ' before the symbol name? 'RANDOMSTRATEGY <=> (quote RANDOMSTRATEGY); it is not a proper function name.
Have you set strategy anywhere? It looks like a scoping issue.
Try this
(setq strategy 'randomstrategy)
(setq move (funcall strategy player board))
Not seeing the code, I'm imagining you're doing something like this:
(defun randomstrategy (a b c) ...)
and then doing this:
(getmove 'randomstrategy x y z)
What you want to do is pass the function "randomstrategy" to getmove using #':
(getmove #'randomstrategy x y z)
In CommonLisp, #' yields the function bound to the symbol, which is
what you want to pass to getmove.
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