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.
Related
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.
Trying my hand at Lisp. I wonder though, why does:
(defun hello(x)
(print x)
)
work fine, but:
(defun hello (x)
(print(x)) ; Fails with EVAL: undefined function X.
)
not?
In LISPs, non-empty, unquoted lists are considered (function, macro, or special form) calls.
So,
(print x)
is a function call to print with an argument x.
But,
(print (x))
is a function call to print with an argument equal to the value of (x). But since (x) is also non-empty list, in order to get the value of (x) there is an attempt to make a call to a non-existent function x with no arguments.
It's key to note that parentheses are not simply grouping syntax as they are in many other languages; they invoke function as well, similar to how X.val is not the same as X.val() in e.g. Python.
So in this case, you are trying to call x as though it were a function. But, depending on what you've passed to hello, x is not a function, and as such cannot be called.
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*)
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.
Emacs Lisp function often start like this:
(lambda () (interactive) ...
What does "(interactive)" do?
Just to clarify (it is in the quoted docs that Charlie cites) (interactive) is not just for key-bound functions, but for any function. Without (interactive), it can only be called programmatically, not from M-x (or via key-binding).
EDIT: Note that just adding "(interactive)" to a function won't necessarily make it work that way, either -- there could be many reasons functions are not interactive. Scoping, dependencies, parameters, etc.
I means that you're including some code for the things you need to make a function callable when bound to a key -- things like getting the argument from CTRL-u.
Have a look at CTRL-h f interactive for details:
interactive is a special form in `C source code'.
(interactive args)
Specify a way of parsing arguments for interactive use of a function.
For example, write
(defun foo (arg) "Doc string" (interactive "p") ...use arg...)
to make ARG be the prefix argument when `foo' is called as a command.
The "call" to `interactive' is actually a declaration rather than a function;
it tells `call-interactively' how to read arguments
to pass to the function.
When actually called, `interactive' just returns nil.
The argument of `interactive' is usually a string containing a code letter
followed by a prompt. (Some code letters do not use I/O to get
the argument and do not need prompts.) To prompt for multiple arguments,
give a code letter, its prompt, a newline, and another code letter, etc.
Prompts are passed to format, and may use % escapes to print the
arguments that have already been read.
Furthermore it’s worth mentioning that interactive's main purpose is, in an interactive context (e.g. when user calls function with key binding), let user specify function arguments that otherwise could be only given programmatically.
For instance, consider function sum returns sum of two numbers.
(defun sum (a b)
(+ a b))
You may call it by (sum 1 2) but you can do it only in a Lisp program (or in a REPL). If you use the interactive special form in your function, you can ask the user for the arguments.
(defun sum (a b)
(interactive
(list
(read-number "First num: ")
(read-number "Second num: ")))
(+ a b))
Now M-x sum will let you type two numbers in the minibuffer, and you can still do (sum 1 2) as well.
interactive should return a list that would be used as the argument list if function called interactively.
(interactive) is for functions meant to interact with the user, be it through M-x or through keybindings.
M-x describe-function RET interactive RET for detailed info on how to use it, including parameter to catch strings, integers, buffer names, etc.
One of the "gotchas" that this clarifies is that the argument to interactive is actually a kind of mini-formatting language (like for printf) that specifies the following (for the surrounding function's input):
schema (number of arguments and their type)
source (e.g., marked-region in buffer and/or user input, etc.)
For example,
'r'
Point and the mark, as two numeric arguments, smallest first.
means that the interactive-annotated function needs exactly two arguments.
e.g. this will work
(defun show-mark (start stop)
(interactive "r")
(print start)
(print stop))
This will break:
(defun show-mark (start)
(interactive "r")
(print start))
Wrong number of arguments: ((t) (start) (interactive "r") (print start)), 2