Undefined Variable i when creating a for loop in common lisp - undefined

I am having a problem getting my solution to project euler problem one to compile, SLIME gives me the error "Undefined variable 'i'" and I have no idea how to solve it hand have been searching for a solution.
(defun sol1 (natnum)
(loop for i from 1 to (1- natnum))
do (if (or (zerop (mod sum i 3))
(zerop (mod sum i 5)))
(incf sum i))
sum)

The variable i is local to the loop expression. The if is outside that loop, so the variable no longer exists.
You also haven't declared or initialized the variable sum. But loop can do summing by itself, so you don't need it.
And you're giving too many arguments to the mod function, it just takes two arguments. I'm not sure why you have sum in there.
(defun sol1 (natnum)
(loop for i from 1 to (1- natnum)
when (or (zerop (mod i 3))
(zerop (mod i 5)))
sum i))
Since you're using SLIME, you must be using Emacs. It has built-in Lisp indentation support, so you should use that to see the structure of your code.

Related

Scheme Error "application: not a procedure"

I'm reading sicp and am writing a program to find the first 3 prime numbers from 1,000. I'm using an altered version of Fermat's method (However the algorithm is irrelevant in this case as I only need to understand the error message). The whole set of code is:
(define (fz-prime number count)
(if (< count 4)
(if (= (fz-fermat-loop number 1) 0)
(fz-prime (+ number 1) count)
((display number) (fz-prime (+ number 1) (+ count 1))))))
(define (fz-fermat-loop number count)
count
(if (> count 5)
1
(if (= (fz-fermat-test number (fz-random number)) 0)
0
(fz-fermat-loop number (+ count 1)))))
(define (fz-fermat-test number count)
(if (= (modulo count number) (modulo (fz-exp-wrapper count number) number))
1
0))
(define (fz-random number)
(random (- number 2)))
(define (fz-exp-wrapper base power)
(fz-exp base power 1))
(define (fz-exp base power result)
(if (<= power 0) result
(fz-exp base (- power 1) (* result base))))
(fz-prime 1000 1)
Now everytime I run the code, it shows the following error:
100910131019. . application: not a procedure;
expected a procedure that can be applied to arguments
given: #<void>
arguments...:
The first 3 numbers are the first three prime numbers, but I don't get what the error message says.
The error message suggests that you're using Racket, but also that you've chosen a language level that disables useful error messages such as the one I get when I copy your program into buffer in the #lang racket language:
if: missing an "else" expression in: (if (< count 4) (if (= (fz-fermat-loop number 1) 0)
(fz-prime (+ number 1) count) ((display number) (fz-prime (+ number 1) (+ count 1)))))
Actually, I bet you're using Jens Axel Soegaard's excellent sicp language, which is entirely the right choice for working through sicp.... but is unfortunately missing some useful error messages.
Specifically, in the language you're using, an if can be missing an else branch, and if the test fails, it silently evaluates to the special # value.
Oh! But wait! You have another problem... you write
((display number) (fz-prime (+ number 1) (+ count 1)))
I bet you're thinking that if you just take two expressions such as (display number) and (fz-prime ...) and wrap them in parens, this means "do the first, then do the second." Actually, though, this means "the first expression evaluates to a function; call it with the arguments that result from evaluating the remaining expressions" and #void is exactly what (display ...) returns.
You might be looking for begin, here, like so:
(begin
(display number)
(fz-prime (+ number 1) (+ count 1)))

Lisp &rest parameters and recursive calls

I have the following Common Lisp Function:
(defun test(A &rest indexes)
(if (null (first indexes))
A
(test (nth (+ 1 (first indexes)) A) (rest indexes))
)
)
As far as I know &rest parameters are treated as a list in the function body but since
(rest indexes) also returns a list I'm stuck with nested Lists as parameters.
For example (test '("a" "b" "c" ("d" "e")) 3 1 6 7)
would cause indexes to be ((1 6 7)) at the second call.
Is there any way to pass my list without having this problem?
Basic style rule: don't use &rest arguments for list processing functions.
Why? Common Lisp implementations are allowed to only support up to the value of CALL-ARGUMENTS-LIMIT number of arguments. This number is 50 or larger, depending on implementation.
This means your function might in some implementation process lists not larger as fifty items.
Better: pass the list as a separate argument.
(defun test (A indexes)
...)
(test '("a" "b" "c" ("d" "e")) '(3 1 6 7))
Wrong solution: don't use apply, since it does not solve the problem of limited argument lists.
CLISP
[1]> call-arguments-limit
4096
[2]> (defun l1 (&rest l) l)
L1
[3]> (apply #'l1 (loop repeat 5000 collect 1))
*** - APPLY: too many arguments given to
#<FUNCTION L1 (&REST L)
(DECLARE (SYSTEM::IN-DEFUN L1))
(BLOCK L1 L)>
The following restarts are available:
ABORT :R1 Abort main loop
rest is a accessor function that is paired together with first to give you the first element and the rest of the list. rest is the same as cdr.
&rest is a lambda list keyword that slurps the remaining arguments in the variable name that follows it.
You are really looking for apply. Imagine I make a function that can take 0 or more numeric parameters and add them together:
(defun add (&rest numbers)
(apply #'+ numbers))
Apply can take more than two arguments. The first is the function to call and all but the last are extra arguments that are put in front of the last arguments element. You are guaranteed the implementation supports 50 arguments or upto the number of arguments a function can take in that particular implementation supports above 50.
(apply #'+ 1 2 '(3 4 5)) ; ==> 15
Now recursing by &rest and apply makes inefficient code so you should use higher order functions, loop macro, or make a helper:
;; higher order function
(defun fetch-indexes (a &rest indexes)
(mapcar (lambda (i) (nth i a)) indexes))
;; loop macro
(defun fetch-indexes (a &rest indexes)
(loop :for i :in indexes
:collect (nth i a)))
;; helper function
(defun fetch-indexes (a &rest indexes)
(labels ((helper (indexes)
(if (endp indexes)
'()
(cons (nth (first indexes) a)
(helper (rest indexes))))))
(helper indexes)))
;; test (works the same with all)
(fetch-indexes '(a b c d) 2 3 0 1)
; ==> (c d a b)
Using apply in recursion should be avoided, but I'll show how it's done.
(defun fetch-indexes (a &rest indexes)
(if (endp indexes)
'()
(cons (nth (first indexes) a)
(apply #'fetch-indexes a (rest indexes)))))
In your example you have nested lists. In order for that to work you would need to flatten it as well. I haven't done that so these supports one proper list of elements.
Another solution, albeit a bit more verbose, but less reliant on details of apply is to use a sub-function for the recursion, which just takes a list. The outer "main" entry point takes the &rest indices syntax, while the inner function takes it as a list:
(defun test (a &rest indices)
(labels ((internal-test (indices)
;; ... the recursion thing calling internal-test
))
(internal-test indices)))
In contrast to the (defun add (&rest args) ... ) example, you might still have some arguments before the rest, which in case of using apply would require you to append those to the variable arguments list.
Of course, as Rainer Joswig pointed out, you need to take care only to use this, when the number of variable args is small.

Higher-Order Function Scheme: Incrementing via Returned Value

I'm having issues with some functionality in Scheme
So in this book i'm learning about Scheme i've come across this problem that I don't quite grasp yet.
It's asking me to create a high order function that does this:
(display ((incrementn 4) 2))
6
I've been stuck on this for a couple of hours and still seem to have not understood the fundamentals. So i'm turning to you all in hopes I can get some better understanding on this functional call.
So the way I understand it so far is that when we define a function like so:
(define (increment n) ______)
The blank spaces obviously represent my following manipulation of the arguments given. What i don't seem to understand is how the high order function returns the outside argument (of the increment function) and injects it into the defined function(which is (incrementn 3) )
I understand fully that 3 is the initial value (integer) that we increment n times (n being the argument passed outside of the ((incrementn n) x) ) that we increment n by 1 x times
The question i'm asking you simply is that given x being an unbound variable (right?) how do I return that integer and increment n by 1 that many times? What is the syntax for this kind of behaviour?
The the point to understand here is that after we call incrementn with 3 as the initial argument it will return a function, and that afterwards 2 is passed as an argument to that function. This is called currying, and the solution is straightforward after you grasp the concept at play here:
(define (incrementn n)
(lambda (x)
(+ n x)))
As you can see, the call to incrementn captures the value of the n parameter in the returned lambda, and when we call it passing x, n is there to be used in the expressions in the body of the lambda. Now, it works as expected:
((incrementn 4) 2)
=> 6
((incrementn -1) 3)
=> 2

I would like to make a macro that would create a function call in Common Lisp

I have a bunch of functions named as follows
(test-1)
(test-2)
(test-3)
(test-n)...
I would like to make a macro or function called '(magically-add)' that would create a function call out of a preset variable value inside the macro or function and a parameter supplied to the macro. For example the preset variable value, lets call the variable 'foo' inside the macro would be
(setf foo test-)
and to create one of the functions at the top of my post the supplied parameter would equal 1, 2, 3 or n.
so when I run it, I would run it as below, choosing '1' in this case and saving the output to a variable with 'defparameter'.
(defparameter bar (magically-add 1))
so now before I enter just "bar" without quotes at the repl I know the contents of it is a function call that looks like this,
(test-1) so when I run 'bar' at the repl
as so
REPL> bar
The output is whatever the output of the function (test-1) would have been had I ran that at the repl. so after running (magically-add) to concatenate, somehow, 'test-' from inside the macro and '"1"' without quotes the variable I supplied to the macro then 'bar' would equal '(test-1)'. So lets say the normal output of '(test-1)' would be '"Hello World"' then running 'bar' at the repl would have the same output as below
OUTPUT>"Hello World"
Anyone like to help me create this 'magical function'? Thanks in advance for any takers.
Edit:
I was wondering what would I do if , lets say this was test-1
(defun test-1 (matrix type row cols)
(find-element matrix type rows cols))
If I called
(defmacro magically-add (matrix type rows cols &optional (base 'test-))
(list (intern (concatenate 'string
(symbol-name base)
(write-to-string type)))))
then
(magically-add hypothetical-matrix double 0 0)
I get: 'Invalid number of arguments 0'
It seem that magically-add will call the function test-1 but would need updating to pass parameters to it...That my ultimate goal to actually pass parameters to magically-add and have the parameters end up as arguments to test-1. Any advice on this?? Thanks again for that genius answer btw.
Edit 2:
I do apologize I was using 'test-1 .. n' as a catch all Previously I added the type as a parameter....but its actually named 'test-double' and the name tells which one, i/e 'test-double' 'test-float' 'test-int', to run. So sorry about that, just a little pitfall of simplifying.
So with your latest edit using my '(test-double)' function as example:
(defun test-double (matrix rows cols)
(find-element matrix rows cols))
I can call '(magically-add 'test- 'double matrix 0 0)' but the only question now is in the beauty of it. I'd like to be able to call instead of
'(magically-add 'test- 'double matrix 0 0)'
just
'(magically-add 'test 'double matrix 0 0)'
So if I rename my function to (testdouble) it's possible but kinda ugly, but if I call
(defun magically-add (base number &rest args)
(apply (intern (concatenate 'string
(symbol-name base)
"-"
(write-to-string number)))
args))
It's possible...Can you give me one last piece of advice, on how would I call with keywords as below. Lisp keywords are so beautiful(different colors and all). Then I can access all my "'test-"' as below....I think that might be the ultimate...especially if its quicker, again High Performance library...but what you provided so far is just awesome I'll have to compare the two for the real winner...Thank you very much for taking the time to help me this.
(magically-add :test :double matrix 0 0)
Will post benchmarking of these functions vs running just the originals later today under this line.
On a hundred thousand runs with a dotimes and nothing else in the dotimes but the function, the original function and Frank's did about the same time 5 seconds on a fresh emacs.
On a billion runs with a dotimes and nothing else in the dotimes but the function the original function and Frank's did drastically different
the original took about 41 seconds to complete a billion iterations...not bad...
Frank's function was understandably slower - It took 41 seconds to complete 20 million iterations and as for a billion...Well I apologize but I stopped counting after 8 minutes...
So if anybody has an idea how to speed up this style of coding to make it comparable I'd love to hear it. Since these are functions for high performance library for now I'll just be craft with the names as C++ libraries do sometimes and call them (test-int) (test-float) (test-double)....etc. For a lot of functions that makes it easy to remember like in c++ doing Mat.at or Mat.cols or Mat.rows.
I hope I understand your idea right. What's about this?
(defun magically-add (number &optional (base 'test-))
(funcall (intern (concatenate 'string
(symbol-name base)
(write-to-string number)))))
It converts the number as well as the base into a string, concatenates it, then converts it back into a symbol for calling it.
Testing:
CL-USER 1 > (defun test-1 () "hello World")
TEST-1
CL-USER 2 > (magically-add 1)
"hello World"
Note that this holds only for dynamically scoped functions – that means it does not work for functions defined with labels or flet. (For a similar reason why you cannot get the value of a lexical scoped symbol – for more details have a look here) If you want to have that, you can use a macro:
(defmacro magically-add (number &optional (base 'test-))
(list (intern (concatenate 'string
(symbol-name base)
(write-to-string number)))))
Now it works for lexically scoped functions, too:
CL-USER 3 > (flet ((test-1 () "Hello again")) (magically-add 1))
"Hello again"
EDIT:
To answer to your problem after your edit – There two major things wrong.
First, you omitted the number variable and converted your new variable type to a string. So you will call a function named test-double that doesn't exist. Second, you call that function without any arguments. You must add them to the function-call.
Here is a version of magically-add that receives arbitrary number of arguments, but you MUST give the base variable to it. It doesn't default to test- anymore. It also uses the DEFUN version because of Rainer Joswigs comment below. Being restricted to only using plain numbers for the number argument (and not variables and not elements of lists) seems to be a greater inconvenience to me than not using lexically scoped functions.
(defun magically-add (base number &rest args)
(apply (intern (concatenate 'string
(symbol-name base)
(write-to-string number)))
args))
So the first two arguments are for contructing the function name and all the rest arguments used to call this function:
CL-USER 1 > (defun test-1 (foo bar baz) (list foo bar baz))
TEST-1
CL-USER 2 > (magically-add 'test- 1 "hi" 42 'symbol)
("hi" 42 SYMBOL)
If someone has an idea how to do something similar to that with not being restricted to dynamically scoped functions, I'd be interested, too.
EDIT 2:
To answer your second edit: There's quiet few to change to achieve that. write-to-string gives you a string of the printed representation of number. Of course, if it's the keyword :double, you'll get ":DOUBLE". You can just use symbol-name again to retrieve the name of the keyword – which is just "DOUBLE".
(defun magically-add (praefix postfix &rest args)
(apply (intern (concatenate 'string
(symbol-name praefix)
"-"
(symbol-name postfix)))
args))

Tail-Recursive Power Function in Scheme

I am having trouble writing a tail-recursive power function in scheme. I want to write the function using a helper function. I know that I need to have a parameter to hold an accumulated value, but I am stuck after that. My code is as follows.
(define (pow-tr a b)
(define (pow-tr-h result)
(if (= b 0)
result
pow-tr a (- b 1))(* result a)) pow-tr-h 1)
I edited my code, and now it works. It is as follows:
(define (pow-tr2 a b)
(define (pow-tr2-h a b result)
(if (= 0 b)
result
(pow-tr2-h a (- b 1) (* result a))))
(pow-tr2-h a b 1))
Can someone explain to me why the helper function should have the same parameters as the main function. I am having a hard time trying to think of why this is necessary.
It's not correct to state that "the helper function should have the same parameters as the main function". You only need to pass the parameters that are going to change in each iteration - in the example, the exponent and the accumulated result. For instance, this will work fine without passing the base as a parameter:
(define (pow-tr2 a b)
(define (pow-tr2-h b result)
(if (= b 0)
result
(pow-tr2-h (- b 1) (* result a))))
(pow-tr2-h b 1))
It works because the inner, helper procedure can "see" the a parameter defined in the outer, main procedure. And because the base is never going to change, we don't have to pass it around. To read more about this, take a look at the section titled "Internal definitions and block structure" in the wonderful SICP book.
Now that you're using helper procedures, it'd be a good idea to start using named let, a very handy syntax for writing helpers without explicitly coding an inner procedure. The above code is equivalent to this:
(define (pow-tr2 a b)
(let pow-tr2-h [(b b) (result 1)]
(if (= b 0)
result
(pow-tr2-h (- b 1) (* result a)))))
Even though it has the same name, it's not the same parameter. If you dug into what the interpreter is doing you'll see "a" defined twice. Once for the local scope, but it still remembers the "a" on the outer scope. When the interpreter invokes a function it tries to bind the values of the arguments to the formal parameters.
The reason that you pass the values through rather mutating state like you would likely do in an algol family language is that by not mutating state you can use a substitution model to reason about the behaviour of procedures. That same procedure called at anytime with arguments will yeild the same result as it is called from anywhere else with the same arguments.
In a purely functional style values never change, rather you keep calling the function with new values. The compiler should be able to write code in a tight loop that updates the values in place on the stack (tail call elimination). This way you can worry more about the correctness of the algorithm rather than acting as a human compiler, which truth be told is a very inefficient machine-task pairing.
(define (power a b)
(if (zero? b)
1
(* a (power a (- b 1)))))
(display (power 3.5 3))