The function is undefined. (recursion) - function

I am writing a simple member function that returns the value associated with that member. The first line of the conditional (to test if the first value is the one we're looking for) works fine, but the recursive part (to test parts of the list that are further along) returns an error every time.
Here is my function:
(defun mem (prop L)
(cond
((eq (caar L) prop) (print cadar L)))
(t (mem (prop (cdr L)))))) // error is on this line!
So, if I enter
(mem `i `((i 1) (j 2)))
it correctly returns 1. However, if I enter
(mem `j `((i 1) (j 2)))
it returns an error that "function prop is undefined."
How do I let the program know that prop isn't a function, but is just an input parameter?
This is my first lisp program, so I'm assuming the answer is incredibly simple, but I have tried many things and have yet to succeed.

The problem in particular is the snippet: (prop (cdr L)). This tries to call prop, passing it (cdr L). To pass it as an argument to mem, simply leave out the extra parentheses: (mem prop (cdr L)).
If you're having a problem figuring out where to put parentheses in general, note that Lisp syntax is very similar to mathematical syntax for functions, except the function goes on the inside of the parentheses (and you use spaces instead of commas, but that isn't a problem here). For example, written in mathematical notation, you have: mem(prop(cdr(L))), instead of mem(prop, cdr(L)).
Other Issues
It looks like you have an extra parentheses after the first branch of the cond, which ends it early. Use an editor/IDE with parentheses matching to catch this sort of error. Emacs does it, as does DrRacket. The former can be used with Common LISP via SLIME (search the web for set-up instructions for your platform), while the latter readily supports Scheme.
The semicolon (";") is the comment character used in most LISPs.
print isn't necessary for this function, and (depending on its behavior) may be incorrect. In some LISPs (e.g. Common LISP), it returns its argument, but in others it may return nil or the instance of some void type.
Quasiquote (aka backquote, backtick) is also unnecessary. Quasiquote lets you quote some symbols, while others (those prefixed with a comma) are replaced with their values. Since you don't need substitution in the quoted expressions, a plain quote will work: (mem 'j '((i 1) (j 2))).
For readability, insert more whitespace between closing and opening parentheses.

Related

How to pass `and` as a function in Racket?

For the following code:
(foldl and #t '(#t #f))
Racket returns:
and: bad syntax in: and
I know and is not a function. And I can circumvent this problem using lambda:
(foldl (lambda (a b) (and a b)) #t '(#t #f))
I have 2 questions here:
and is not a function. Then what is it? Is it a macro?
My solution using lambda seems ugly. Is there a better way to solve this problem?
Thank you.
It is a conditional syntactic form, or it might be implemented as a macro that expands to some core syntax form, which is treated as a special case by the compiler/interpreter.
The list there in Racket's docs includes if as a special form but doesn't include and, so the latter most probably is implemented in terms of the former. But R5RS does list and as a syntactic keyword. So, best we can say, it's either a special syntax, or a macro.
It is easy to re-write any and form (and a b c ...) as an if form, (if a (if b (if c #t #f) #f) #f).
lambda is fine by me, but you can also use every from SRFI-1 (or Racket's andmap):
(every identity '(#t #f))
should return #f.
edit: except, as Joshua Taylor points out, calling your lambda through a function like foldl does not short-circuit. Which defeats the purpose to calling the and in the first place.
Another thing is, in Racket's foldl the last argument to lambda is the one that receives the previous result in the chain of applications; so the implementation should really be
(foldl (lambda (a b) (and b a)) #t '(#t #f))

Emacs defining a function that sets arguments to nil

I would like to create a nil function that takes any number of symbols and sets them all to nil.
(defun clean (as many args as given by user)
(setq each-arg nil)
)
(clean x y z)
How to do this 'cleanly'?
Since you're not quoting the arguments, it has to be a macro:
(defmacro clean (&rest symbols)
`(progn
,#(mapcar (lambda (sym) (list 'setq sym 'nil))
symbols)))
Similar idea as Dmitry, but generates slightly less code:
(defmacro clean (&rest variables)
`(setq ,#(loop for var in variables nconc (list var nil))))
(macroexpand '(clean a b c d))
;; (setq a nil b nil c nil d nil)
Regarding your other questions:
simple, but time consuming way to know is to move the point to the function that you don't know and C-h f or M-xdescribe-function this will put the function name in the prompt (if it is indeed an Emacs Lisp function) and show the description and, if availably the location in the source code.
I'll try to explain, but I'm no language reference :)
defmacro - is similar to function, but it doesn't evaluate arguments. Macros are executed when your code is read and compiled into the bytecode. Their primary goal is to generate other code.
lambda - is a macro that creates an anonymous function and returns it.
mapcar - is a high-order function that applies a function to all elements of the list in succession and collects the result into a list in the order it applied the function.
&rest - is a special keyword in the function's lambda-list (i.e. the definition of parameters) which means literally that the identifier following this symbol is a list of all arguments on the right of it).
,# is a special operator used in macros, inside back-quote macros. It instructs the reader that the expression following it must be evaluated, treated as list, and all of its conses must be appended to the form that is being currently parsed.

Is the Macro argument a function?

I am trying to determine whether a given argument within a macro is a function, something like
(defmacro call-special? [a b]
(if (ifn? a)
`(~a ~b)
`(-> ~b ~a)))
So that the following two calls would both generate "Hello World"
(call-special #(println % " World") "Hello")
(call-special (println " World") "Hello")
However, I can't figure out how to convert "a" into something that ifn? can understand. Any help is appreciated.
You might want to ask yourself why you want to define call-special? in this way. It doesn't seem particularly useful and doesn't even save you any typing - do you really need a macro to do this?
Having said that, if you are determined to make it work then one option would be to look inside a and see if it is a function definition:
(defmacro call-special? [a b]
(if (#{'fn 'fn*} (first a))
`(~a ~b)
`(-> ~b ~a)))
This works because #() function literals are expanded into a form as follows:
(macroexpand `#(println % " World"))
=> (fn* [p1__2609__2610__auto__]
(clojure.core/println p1__2609__2610__auto__ " World"))
I still think this solution is rather ugly and prone to failure once you start doing more complicated things (e.g. using nested macros to generate your functions)
First, a couple of points:
Macros are simply functions that receive as input [literals, symbols, or collections of literals and symbols], and output [literals, symbols, or collections of literals and symbols]. Arguments are never functions, so you could never directly check the function the symbol maps to.
(call-special #(println % " World") "Hello") contains reader macro code. Since reader macros are executed before regular macros, you should expand this before doing any more analysis. Do this by applying (read-string "(call-special #(println % \" World\") \"Hello\")") which becomes (call-special (fn* [p1__417#] (println p1__417# "world")) "Hello").
While generally speaking, it's not obvious when you would want to use something when you should probably use alternative methods, here's how I would approach it.
You'll need to call macroexpand-all on a. If the code eventually becomes a (fn*) form, then it is guaranteed to be a function. Then you can safely emit (~a ~b). If it macroexpands to eventually be a symbol, you can also emit (~a ~b). If the symbol wasn't a function, then an error would throw at runtime. Lastly, if it macroexpands into a list (a function call or special form call), like (println ...), then you can emit code that uses the thread macro ->.
You can also cover the cases such as when the form macroexpands into a data structure, but you haven't specified the desired behavior.
a in your macro is just a clojure list data structure (it is not a function yet). So basically you need to check whether the data structure a will result is a function or not when it is evaluated, which can be done like show below:
(defmacro call-special? [a b]
(if (or (= (first a) 'fn) (= (first a) 'fn*))
`(~a ~b)
`(-> ~b ~a)))
By checking whether the first element of the a is symbol fn* or fn
which is used to create functions.
This macro will only work for 2 cases: either you pass it a anonymous function or an expression.

Interactive "r" elisp defun with additional args?

Is it possible to write an interactive defun with code "r" that has an additional optional argument (so that it does things within the selected region, but with another argument)? I would like something like the following:
(defun my-function (start end &optional arg)
"Do something with selected region"
(interactive "r")
(if arg
(setq val arg)
(setq val 2))
(do things...))
Looking at the documentation it says
'r': Point and the mark, as two numeric
arguments, smallest first. This is the
only code letter that specifies two
successive arguments rather than one.
No I/O.
I'm not sure if the 'No I/O' and 'two successive arguments' means that it takes 2 and only 2 arguments (i.e., limited to the region's start and end point as args). Although it allows me to evaluate and run the defun with an additional argument, Emacs appears to be ignoring it.
Thank you.
To make interactive ask for multiple parameters, separate them with a newline character. For instance, if you want your third parameter be bound to the value of the prefix argument, define your function like this:
(defun my-function (start end &optional arg)
"Do something with selected region"
(interactive "r\np")
(if arg
(setq val arg)
(setq val 2))
(do things...))
M-x describe-function interactive gives you further information.
A function can be called in two ways:
Interactively: This is what happens when a user calls the command, e.g. when it has been bound to a key.
From lisp: When the function is called from another lisp function. e.g. (r 100 200 t).
In your case, you have to make sure that the arguments match the interactive specification, in this case it must accept two arguments. The third will not be used when called interactively (so then it will get the value nil).
NO I/O means that it will not prompt the user for input (like it does when it asks for a file name).
If you want your function to act differently depending in when the region is active, you could ask the function (use-region-p).

what's going on when I setq a parameter variable in a defun? (Emacs)

(defun make-it-5 (num)
(setq num 5))
(setq a 0)
(make-it-5 a)
;; now a is still 0, not 5.
In the above code, it seems neither (setq a 5) nor (setq 0 5) happens. If (setq a 5) happened, then a would have changed to 5, but a is still 0. If (setq 0 5) happened, Lisp error would have occurred. What does happen? That is my question.
For some of you who got here by googling and wondering how to make make-it-5 work as its name suggest, one way is
(defmacro make-it-7 (num) ; defmacro instead of defun
`(setq ,num 7))
(setq a 0)
(make-it-7 a)
;; now a is 7.
Another is:
(defun make-it-plus (num-var)
(set num-var (+ 1 (symbol-value num-var))) ; `set' instead of `setq'
)
(setq a 0)
(make-it-plus 'a) ; 'a instead of a
;; now a is 1.
The short answer is that the (setq num 5) changes the binding for num, which is a binding local to the make-it-5 function.
A breakdown follows. It's good to make sure you're familiar with the notion of evaluation.
When the (make-it-5 a) is evaluated, the interpreter looks for a function in the first element of the expression. In this case, the first element is a symbol (make-it-5 - which means it is a named function), so it looks in the symbol's function cell. Note: this lookup can repeat itself, see Symbol Function Indirection.
The rest of the elements of the expression are evaluated to find values. In this case, there's just one symbol (a), and so the interpreter returns the contents of its value cell, which is 0.
The interpreter then applies the function to the list of arguments, which involves making local bindings between its arguments to the values passed in. In this case, a local binding between the symbol num and the value 0 is made. Then the body of the function is evaluated in that environment.
The body is just a single expression which is a "call" to setq. I put "call" in quotes because setq is a special form and doesn't evaluate its first argument, but looks up the symbol and sets the most local existing binding, which is the binding created inside the function make-it-5.
So, you're changing the binding for the symbol num which is local to the function make-it-5.