Is there a way to specify keyword arguments to a function as a dictionary, analogously to the . that allows us to supply a list for positional arguments? I'm looking for something analogous to python's *args and **kwargs.
In more detail:
If we want to handle an arbitrary number of positional arguments in a function, we can define it like so:
(define (my-add . args)
(apply + args))
and use it with a variable number of arguments as:
(define numbers '(1 2 3))
(apply my-add numbers) ;=> 6
(define numbers '(1 2 3 4 5))
(apply my-add numbers) ;=> 15
Even for functions that don't explicitly handle the "rest" of the positional arguments via the . syntax, we can use apply to unpack positional arguments from a list.
(apply expt '(2 3)) ;=> 8
I see that apply does forward on keyword arguments in addition to positional arguments. However, this only works if the invoked function itself identifies the specific keyword arguments it is expecting. For instance, in a dispatch situation where the function doesn't itself use the keyword arguments but merely intends to forward them on to some appropriate handler, using apply in this way doesn't do what we need because the function would need to know about all the keyword arguments accepted by any function it is dispatching to, not to mention do the legwork of repacking them in some way before invoking the handlers.
As a tangible example illustrating the problem, consider a simple "echo args" function that echoes all of the arguments passed to it:
(define (echo-args . args)
(printf "~a" args))
With only positional args:
> (echo-args 1 2 5)
(1 2 5)
With keyword args:
> (echo-args 1 2 5 #:key 'hi)
; application: procedure does not accept keyword arguments
; procedure: echo-args
; arguments...:
; 1
; 2
; 5
; #:key 'hi
; Context:
; /Applications/Racket v7.5/collects/racket/repl.rkt:11:26
Is there a built-in way to accomplish this kind of thing? If not, any ideas on how to make this work?
What you are looking for is make-keyword-procedure. This generates a procedure that accepts all keyword arguments, and can be accessed from a dictionary.Taking the example from the docs:
> (define show
(make-keyword-procedure (lambda (kws kw-args . rest)
(list kws kw-args rest))))
> (show #:blue 3 4)
'((#:blue) (3) (4))
Of course, a dictionary implemented as two lists can be a bit annoying. So Alex Knauth made a small package hash-lambda which gives you a more direct hash-map like API.
Related
I am going through a lisp book and I am looking at mapcar, my question is why is that this is valid:
> (mapcar #'+ '(1 2) '(3 4))
but this one isn't:
(mapcar + '(1 2) '(3 4))
in other words, is there a reason it was decided in lisp that the first argument to mapcar cannot be the function itself, and has to be its name? what purpose does this serve?
is there a reason it was decided in lisp that the first argument to mapcar cannot be the function itself, and has to be its name? what purpose does this serve?
It's just that in something like Common Lisp, the identifier + has multiple different purposes. It is a variable, a function, plus various other things.
writing + means the variable. It is used by the read eval print loop. The value of + is the last form that was evaluated, the value of ++ is the previous value of +, and the value of +++ is the previous value of ++.
To tell Common Lisp that you want to use the function value of an identifier +, one has to write (function +) or shorter #'+.
Thus
(mapcar (function +) '(1 2) '(3 4))
or shorter
(mapcar #'+ '(1 2) '(3 4))
actually means call mapcar with the function + and the lists (1 2) and (3 4)
There are two other ways to use the function +.
(mapcar '+ '(1 2) '(3 4))
Above will have Lisp retrieve the global function value of the symbol +.
Fourth, we can also have the function object be a part of the source code.
#'+ is a function. Common Lisp is what's called a 'lisp 2', which means that it has two namespaces: during evaluation of a compound form, like (+ a b), the function position is looked up in the function namespace while the other positions are looked up in the value namespace. This means that, for instance (append list list) does not make a list whose two elements are the list function: it makes a list whose two elements are whatever list happens to be bound to as a value.
But sometimes you need to get the function value of a name in a value position: an example is in the first argument of mapcar. To do that there is a special operator, function: (mapcar (function +) x y) adds the elements of two lists. Like quote, function has a read macro, which is #'.
(To make this more fun, mapcar actually expects a function designator so you can use the nsme of a function: (mapcar '+ x y) will work, although it is a bit horrid.)
How can I get the number of arguments supplied to a Lisp function like in bash with the variable $0? (I saw a similar question but it does not give the answer.)
It's not clear exactly what you're asking, but in Common Lisp you can use an &rest argument to collect an indeterminate number of arguments into a list. Using length you can see how many were provided. For instance:
CL-USER> (defun numargs (&rest arguments)
(length arguments))
NUMARGS
CL-USER> (numargs 1 2 3)
3
CL-USER> (numargs 1 2 3 4 5)
5
CL-USER> (numargs)
0
Since the question has the sbcl tag, you might be interested in SBCL-specific solutions. sb-introspect:function-lambda-list looks relevant:
CL-USER> (sb-introspect:function-lambda-list 'cons)
(SB-IMPL::SE1 SB-IMPL::SE2)
CL-USER> (sb-introspect:function-lambda-list 'numargs)
(&REST ARGUMENTS)
If you examine the lambda list, you can determine how many arguments a function can take.
I have two macros. The first one takes a symbol as the only parameter (because it's passed to def, which needs a symbol). The second function takes a list of symbols and should call the first with each symbol individually.
(defmacro m1 [s]
'(let [f# ... dynamic function definition ...]
(def ~s f#))
The second macro should take a list of symbols and pass them to the first, but I can't get it to work. The best I could come up with was the following:
(defmacro m2 [symbols]
`(for [s# ~symbols] (eval (read-string (str "(name.of.current.namespace/m1 " s# ")")))))
which forces the s# to be evaluated before it is passed to the first macro. It is also invoked with a list of strings, rather than a list of symbols.
This is useful for a library which I am using for which all of the functions in the library takes the same two first parameters. I am trying to create wrapper functions, in my namespace, for some of the functions, which automatically provides the first two parameter values which are common to all of them.
Any ideas to improve this?
Usually when you ask how to get two macros to cooperate, the answer is to not make them both macros. I think my blog post on macro-writing macros will help clarify. For this particular situation I'd probably combine two suggestions from the comments:
(defmacro build-simpler-functions [& names]
(cons 'do
(for [name names]
`(def ~(symbol (str "simple-" name))
(partial ~name 5 10))))) ; if you always pass 5 and 10
(build-simpler-functions f1 f2)
This expands to
(do
(def simple-f1 (clojure.core/partial f1 5 10))
(def simple-f2 (clojure.core/partial f2 5 10)))
which looks like basically what you want.
Edit: if the args you "always" pass are different for each function, you can do this:
(defmacro build-simpler-functions [& names]
(cons 'do
(for [[name & args] names]
`(def ~(symbol (str "simple-" name))
(partial ~name ~#args)))))
(build-simpler-functions [f1 5 10] [f2 "Yo dawg"]) ; expansion similar to the previous
If in the REPL I do this:
(dolist (x (1 2 3))
(print x))
then I get an error since in (1 2 3) the digit 1 is not a symbol or a lambda expr.
If I do:
(dolist (x (list 1 2 3))
(print x))
then it works ok.
My question is why the following works:
REPL> (defmacro test (lst)
(dolist (x lst)
(print x)))
=> TEST
REPL> (test (1 2 3))
1
2
3
=>NIL
Why does dolist accept (1 2 3) when it is inside the macro definition but not when directly in the repl?
The assumption:
"Since TEST is a macro ,it does not evaluate its arguments, so (1 2 3) is passed as is to the dolist macro. So dolist must complain like it does when it is passed (1 2 3) in the REPL"
is obviously wrong. But where?
UPDATE: Although the answers help clarify some misunderstandings with macros, my question still stands and i will try to explain why:
We have established that dolist evaluates its list argument(code blocks 1, 2). Well, it doesnt seem to be the case when it is called inside a macro definition and the list argument that is passed to it is one of the defined macro arguments(code block 3). More details:
A macro, when called, does not evaluate its arguments. So my test macro, when it is called, will preserve the list argument and will pass it as it is to the dolist at expansion time. Then at expansion time the dolist will be executed (no backquotes in my test macro def). And it will be executed with (1 2 3) as argument since this is what the test macro call passed to it. So why doesnt it throw an error since dolist tries to evaluate its list argument, and in this case its list argument (1 2 3) is not evaluatable. I hope this clears my confusion a bit.
This form:
(defmacro test (lst)
(dolist (x lst)
(print x)))
defines a macro, which is a "code transformation function" which
gets applied to a form using this macro at macro expansion time. So,
after you have defined this macro, when you evaluate this expression:
(test (1 2 3))
it first gets read to this list:
(test (1 2 3))
Then, since Lisp reads test at the operator position, it gets
macro-expanded by passing the argument, which is the literal list (1
2 3), to the macro expansion function defined above. This means that
the following gets evaluated at macro-expansion time:
(dolist (x '(1 2 3))
(print x))
So, at macro-expansion time, the three values get printed. Finally,
the return value of that form is returned as the code to be compiled
and executed. Dolist returns nil here, so this is the code returned:
nil
Nil evaluates to nil, which is returned.
Generally, such a macro is not very useful. See "Practical Common
Lisp" by Peter Seibel or "On Lisp" by Paul Graham for an introduction
to useful macros.
Update: Perhaps it is useful to recapitulate the order of
reading, expanding, and evaluating Lisp code.
First, the REPL takes in a stream of characters: ( t e s t
( 1 2 3 ) ), which it assembles into
tokens: ( test ( 1 2 3 ) ).
Then, this is translated into a tree of symbols: (test (1 2
3)). There may be so-called reader macros involved in this step.
For example, 'x is translated to (quote x).
Then, from the outside in, each symbol in operator position (i.e., the
first position in a form) is examined. If it names a macro, then the
corresponding macro function is invoked with the code (i.e., the
subtrees of symbols) that is the rest of the form as arguments. The
macro function is supposed to return a new form, i.e. code, which
replaces the macro form. In your case, the macro test gets the code
(1 2 3) as argument, prints each of the symbols contained within
(note that this is even before compile time), and returns nil,
throwing its arguments away (the compiler never even sees your little
list). The returned code is then examined again for possible
macroexpansions.
Finally, the expanded code that does not contain any macro invocations
anymore is evaluated, i.e. compiled and executed. Nil happens to
be a self-evaluating symbol; it evaluates to nil.
This is just a rough sketch, but I hope that it clears some things up.
Your macro test does not return any code. And yes, macro arguments are not evaluated. If you want to see the same error, you have to define your macro as:
(defmacro test (lst)
`(dolist (x ,lst)
(print x)))
Generally when you have questions about macro expansions, referring to MACROEXPAND-1 is a great first step.
* (macroexpand-1 '(test (1 2 3)))
1
2
3
NIL
T
IE, what is happening is that the actual expansion is that sequence of prints.
Nil is what is returned by DOLIST, and is the expanded code.
Macros get their arguments passed unevaluated. They may choose to evaluate them. dolist does that for its list argument. It works with an unquoted list passed in for lst in your macro test:
(defmacro test (lst)
(dolist (x lst)
(print x)))
That's because at macro-expansion time the dolist sees lst as its argument. So when it evaluates it, it gets the list (1 2 3).
lst is a variable, when expand macro test, it also mean eval dolist structure. the first step is to eval the form lst, will get the lisp object (1 2 3).
like follow example:
(defmacro test (a)
(+ a 2))
(test 2) --> 4 ; mean invoke add function, and the first variable a binding a value 2.
What does the &rest mean in this: (append &rest sequences)
I have finished the book "elisp_intro",but I didn't find the answer. I will be very grateful if you can help me.
It indicates that the following argument is the "rest" argument. In the case of your example, sequences is the rest argument.
Unlike a normal argument, the rest argument will consume the "rest" of any parameters provided by the user. It is a way of making a function that accepts a variable number of arguments. Inside the function body, the argument will be a list containing all of the extra parameters.
So if you had a function that looked like (add &rest numbers), then you could call it like (add 1 2 3 4 5), and within the function the numbers argument would have the value (1 2 3 4 5).
Or for example, ((lambda (a &rest r) r) 1 2 3) ;=> (2 3)
Any arguments following the &rest symbol in a function definition will be collected into a single list object. So in the case of (append &rest sequences), if you call the function:
(append 1)
the variable sequences will be the list (1) in the body of the function. If you call it as
(append 1 2 3)
the variable sequences will be the list (1 2 3) in the body of the function. This is explained in the Elisp Reference manual, in the argument list node.
(info "(elisp)Argument List")
elisp/Common Lisp &rest is analogous to the *args parameter in Python
If you put this in your Common Lisp repl and call foo with varying numbers of arguments, you will see what's up quite quickly.
(defun foo (a b &rest trailing)
(format t "~a :: ~a :: ~a~%" a b trailing))