Common Lisp: Beginner's trouble with funcall - lisp

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.

Related

Setf function names

Reading this question got me thinking about what constitutes a valid car of an expression. Obviously, symbols and lambdas can be "called" using the usual syntax. According to the hyperspec,
function name n. 1. (in an environment) A symbol or a list (setf symbol) that is the name of a function in that environment. 2. A symbol or a list (setf symbol).
So, theoretically, (setf some-name) is a function name. I decided to give it a try.
(defun (setf try-this) ()
(format t "Don't name your functions like this, kids :)"))
((setf try-this))
(funcall '(setf try-this))
(setf (try-this))
GNU CLISP, SBCL, and ABCL will all let me define this function. However, SBCL and ABCL won't let me call it using any of the syntaxes shown in the snippet. CLISP, on the other hand, will run the first two but still errs on the third.
I'm curious about which compiler is behaving correctly. Since SBCL and ABCL agree, I would hazard a guess that a correct implementation should reject that code. As a second question, how would I call my incredibly-contrived not-useful function from the code snippet, since the things I tried above aren't working portably. Or, perhaps more usefully,
A SETF function has to take at least one argument, which is the new value to be stored in the place. It can take additional arguments as well, these will be filled in from arguments in the place expression in the call to SETF.
When you use SETF, it has to have an even number of arguments: every place you're assigning to needs a value to be assigned.
So it should be:
(defun (setf try-this) (new-value)
(format t "You tried to store ~S~%" new-value))
(setf (try-this) 3)
(funcall #'(setf try-this) 'foo)
You can't use
((setf try-this) 'bar)
because the car of a form does not contain a function name. It can only be a symbol or a lambda expression (although implementations may allow other formats as extensions).

Why a parameter of an Emacs lisp function is not evaluated?

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.

Lisp - function that returns a function

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

Common Lisp, reference to value and actual value

Consider this piece of code:
(defvar lst '(1 1))
(defmacro get-x (x lst)
`(nth ,x ,lst))
(defun get-y (y lst)
(nth y lst))
Now let us assume that I want to change the value of the elements of the list called lst, the car with get-x and the cdr with get-y.
As I try to change the value with get-x (with setf) everything goes fine but if I try it with get-y it signals an error (shortened):
; caught STYLE-WARNING:
; undefined function: (SETF GET-STUFF)
Why does this happen?
I myself suspect that this happens because the macro simply expands and the function nth simply returns a reference to the value of an element in the list and the function on the other hand evaluates the function-call to nth and returns the value of the referenced value (sounds confusing).
Am I correct in my suspicions?
If I am correct then how will one know what is simply a reference to a value and an actual value?
The error does not happen with the macro version, because, as you assumed, the expression (setf (get-x some-x some-list) some-value) will be expanded (at compile-time) into something like (setf (nth some-x some-list) some-value) (not really, but the details of setf-expansion are complex), and the compiler knows, how to deal with that (i.e., there is a suitable setf expander defined for function nth).
However, in the case of get-y, the compiler has no setf expander, unless you provide one. The easiest way to do so would be
(defun (setf get-y) (new-value x ls) ; Note the function's name: setf get-y
(setf (nth x ls) new-value))
Note, that there are a few conventions regarding setf-expanders:
The new value is always provided as the first argument to the setf function
All setf functions are supposed to return the new value as their result (as this is, what the entire setf form is supposed to return)
There is, BTW, no such concept as a "reference" in Common Lisp (at least not in the C++ sense), though there once were Lisp dialects which had locatives. Generalized place forms (ie., setf and its machinery) work very differently from plain C++ style references. See the CLHS, if you are curious about the details.
SETF is a macro.
The idea is that to set and read elements from data structures are two operations, but usually require two different names (or maybe even something more complex). SETF now enables you to use just one name for both:
(get-something x)
Above reads a datastructure. The inverse then simply is:
(setf (get-something x) :foobar)
Above sets the datastructure at X with :FOOBAR.
SETF does not treat (get-something x) as a reference or something like that. It just has a database of inverse operations for each operation. If you use GET-SOMETHING, it knows what the inverse operation is.
How does SETF know it? Simple: you have to tell it.
For The NTH operation, SETF knows how to set the nth element. That's builtin into Common Lisp.
For your own GET-Y operation SETF does not have that information. You have to tell it. See the Common Lisp HyperSpec for examples. One example is to use DEFUN and (SETF GET-Y) as a function name.
Also note following style problems with your example:
lst is not a good name for a DEFVAR variable. Use *list* as a name to make clear that it is a special variable declared by DEFVAR (or similar).
'(1 2) is a literal constant. If you write a Common Lisp program, the effects of changing it are undefined. If you want to change a list later, you should cons it with LIST or something like COPY-LIST.

Why should I use 'apply' in Clojure?

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