Unanticipated error when using a cond statement - common-lisp

New to common lisp and having a very rookie problem. My function of one variable is supposed to return the absolute of of the entered variable. It works for when the variable is above or equal to 0 but not below, I suspect this is due to the cond function but i'm not sure.
I have tried the code with brackets and without but cannot see why it is failing. I know this is not the best way of solving this problem but i am just trying to get used to the cond statement at this stage.
(defun abs-x (x)
(cond ((> x 0) x)
((= x 0) 0)
((< x 0) (-x))))
The error message when a variable below 0 is entered is '-X is undefined.

Use
(- x)
; ^
; |
; The space
; is important.
instead of (-x).
That's because - is a valid character in an identifier, so -x is a valid function name. With the space between - and x, though, it calls the function - which takes one or more arguments.

Shorter:
(defun abs-x (x)
(cond ((> x 0) x)
(t (- x))))
Reduced number of checkings using the fact that (- 0) also evaluates to0.
Instead of <= for the last check, use the simpler t - the else in common lisp cond clauses.
With if this would be:
(defun abs-x (x)
(if (> x 0)
x
(- x)))

Related

How does this count-even racket function work?

I am trying to understand how the count-even function given in my textbook works and I'm not sure if I completely understand it.
I have provided my understanding of the function in comments next to code. Can someone explain what is happening and correct me in each step of this function.
And I don't understand how this function is recursive. What is the base case ?
(define (ce x) ; x is an argument that takes in a list
(if (pair? x) ; I don't understand why this is here
(+ (ce (car x)) ; Add the resuls of recursive call together (0 or 1)
(ce (cdr x)))
(if (and (number? x) (even? x)) ; if x is a number and x is even then return 1 ? Else return 0 ?
1
0) ) )
In a recursive function there are usually two cases:
The result is a call to the same function
The result is a simple value, the base case
You choose between the two cases with an if.
Hence the base case is:
(if (and (number? x) (even? x))
1
0) ) )
And the recursive case is:
(+ (count-evens (car x))
(count-evens (cdr x)))
Comments:
The argument x doesn't need to be a list. pairs? tests for a list. If it is just a value then we have the base case. If an even number then result is one, else zero.
If the argument x is a list, we split it into two parts, the head (car) and the tail (cdr). The head is just a value, and so when we rerun count-evens on it we end up with the base case.
The tail is passed to count-evens which keeps slicing off a value at a time until we have a value in the car and empty list in cdr. In the base case, the first value is assessed for an even number, and the empty list is always evaluated as zero.

How do I turn #<unspecified> into a number in guile scheme

I'm trying to get the hang of recursion in scheme. I put together a Fibinachi function and it keeps returning unspecified instead of a number. How do I make this function return a number and to unspecified?
(define (F n)
(if (= n 0)
0)
(if (= n 1)
1)
(if (< n 2)
(+
(F (- n 1))
(F (- n 2)))))
(display (F 5))
(newline)
The function returns
#<unspecified>
I'm using guile (GNU Guile) 2.0.13.
The issue here is that your code is:
(begin
(if a 1)
(if b 2)
(if c 3))
What is wrong with this? The value of that will be unspecified except if c is true.
Why? The value of each if is unspecified when the condition is false. The begin returns the value of the last expression.
Where did the begin come from you might ask as it didn't appear in my code? To make it easier every lambda and define contains an implicit begin which is why your code was even accepted for execution.
You should use either nested ifs or a cond form:
(if a 1
(if b 2
(if c 3)))
(cond (a 1)
(b 2)
(c 3))

Recursive Factorial Function in Common-Lisp

Ok, I'm been learning COMMON LISP programming and I'm working on a very simple program to calculate a factorial of a given integer. Simple, right?
Here's the code so far:
(write-line "Please enter a number...")
(setq x (read))
(defun factorial(n)
(if (= n 1)
(setq a 1)
)
(if (> n 1)
(setq a (* n (factorial (- n 1))))
)
(format t "~D! is ~D" n a)
)
(factorial x)
Problem is, when I run this on either CodeChef or Rexter.com, I get a similar error: "NIL is NOT a number."
I've tried using cond instead of an if to no avail.
As a side note, and most bewildering of all, I've seen a lot of places write the code like this:
(defun fact(n)
(if (= n 1)
1
(* n (fact (- n 1)))))
Which doesn't even make sense to me, what with the 1 just floating out there with no parentheses around it. However, with a little tinkering (writing additional lines outside the function) I can get it to execute (equally bewildering!).
But that's not what I want! I'd like the factorial function to print/return the values without having to execute additional code outside it.
What am I doing wrong?
One actually needs to flush the I/O buffers in portable code with FINISH-OUTPUT - otherwise the Lisp may want to read something and the prompt hasn't yet been printed. You better replace SETQ with LET, as SETQ does not introduce a variable, it just sets it.
(defun factorial (n)
(if (= n 1)
1
(* n (factorial (- n 1)))))
(write-line "Please enter a number...")
(finish-output) ; this makes sure the text is printed now
(let ((x (read)))
(format t "~D! is ~D" x (factorial x)))
Before answering your question, I would like to tell you some basic things about Lisp. (Neat fix to your solution at the end)
In Lisp, the output of every function is the "last line executed in the function". Unless you use some syntax manipulation like "return" or "return-from", which is not the Lisp-way.
The (format t "your string") will always return 'NIL as its output. But before returning the output, this function "prints" the string as well.
But the output of format function is 'NIL.
Now, the issue with your code is the output of your function. Again, the output would be the last line which in your case is:
(format t "~D! is ~D" n a)
This will return 'NIL.
To convince yourself, run the following as per your defined function:
(equal (factorial 1) 'nil)
This returns:
1! is 1
T
So it "prints" your string and then outputs T. Hence the output of your function is indeed 'NIL.
So when you input any number greater than 1, the recursive call runs and reaches the end as input 1 and returns 'NIL.
and then tries to execute this:
(setq a (* n (factorial (- n 1))))
Where the second argument to * is 'NIL and hence the error.
A quick fix to your solution is to add the last line as the output:
(write-line "Please enter a number...")
(setq x (read))
(defun factorial(n)
(if (= n 1)
(setq a 1)
)
(if (> n 1)
(setq a (* n (factorial (- n 1))))
)
(format t "~D! is ~D" n a)
a ;; Now this is the last line, so this will work
)
(factorial x)
Neater code (with Lisp-like indentation)
(defun factorial (n)
(if (= n 1)
1
(* n (factorial (- n 1)))))
(write-line "Please enter a number...")
(setq x (read))
(format t "~D! is ~D" x (factorial x))
Common Lisp is designed to be compiled. Therefore if you want global or local variables you need to define them before you set them.
On line 2 you give x a value but have not declared the existence of a variable by that name. You can do so as (defvar x), although the name x is considered unidiomatic. Many implementations will give a warning and automatically create a global variable when you try to set something which hasn’t been defined.
In your factorial function you try to set a. This is a treated either as an error or a global variable. Note that in your recursive call you are changing the value of a, although this wouldn’t actually have too much of an effect of the rest of your function were right. Your function is also not reentrant and there is no reason for this. You can introduce a local variable using let. Alternatively you could add it to your lambda list as (n &aux a). Secondarily your factorial function does not return a useful value as format does not return a useful value. In Common Lisp in an (implicit) progn, the value of the final expression is returned. You could fix this by adding a in the line below your format.
For tracing execution you could do (trace factorial) to have proper tracing information automatically printed. Then you could get rid of your format statement.
Finally it is worth noting that the whole function is quite unidiomatic. Your syntax is not normal. Common Lisp implementations come with a pretty printer. Emacs does too (bound to M-q). One does not normally do lots of reading and setting of global variables (except occasionally at the repl). Lisp isn’t really used for scripts in this style and has much better mechanisms for controlling scope. Secondarily one wouldn’t normally use so much mutating of state in a function like this. Here is a different way of doing factorial:
(defun factorial (n)
(if (< n 2)
1
(* n (factorial (1- n)))))
And tail recursively:
(defun factorial (n &optional (a 1))
(if (< n 2) a (factorial (1- n) (* a n))))
And iteratively (with printing):
(defun factorial (n)
(loop for i from 1 to n
with a = 1
do (setf a (* a i))
(format t “~a! = ~a~%” i a)
finally (return a)))
You can split it up into parts, something like this:
(defun prompt (prompt-str)
(write-line prompt-str *query-io*)
(finish-output)
(read *query-io*))
(defun factorial (n)
(cond ((= n 1) 1)
(t (* n
(factorial (decf n)))))
(defun factorial-driver ()
(let* ((n (prompt "Enter a number: "))
(result (factorial n)))
(format *query-io* "The factorial of ~A is ~A~%" n result)))
And then run the whole thing as (factorial-driver).
Sample interaction:
CL-USER 54 > (factorial-driver)
Enter a number:
4
The factorial of 4 is 24

Trying to create a recursive function in scheme?

I'm having a little trouble creating a recursive function in Scheme. I need to create a function called foo(x) that recursively does the addition of all the powers. For example foo(5) would be 5^4 + 4^3 + 3^2 + 2^1 + 1^0 = 701.
The stopping condition is if x = 0 then return zero. Else then return x^x-1 + foo(x-1)
Here's what I have so far for my function:
(define (foo x)
(cond ((zero? x) 0)
(else (+(expt(x (- x 1)))foo(- x 1)))))
You just have to be more careful with the parentheses, in particular notice that the correct way to call a procedure is like this: (foo x), instead of this: foo(x). This should work:
(define (foo x)
(cond ((zero? x) 0)
(else (+ (expt x (- x 1))
(foo (- x 1))))))
(foo 5)
=> 701
Allow me to ident the code. I just pasted it in DrRacket and hit CTRL+I then put the arguments to + on one line each:
(define (foo x)
(cond ((zero? x) 0)
(else (+ (expt (x (- x 1)))
foo
(- x 1)))))
So the base case is ok, but your default case looks very off. x is treated as a procedure since it has parentheses around it and - also uses x as if it's a number. It can't be both.
foo is not applied since it doesn't have parentheses around it so it evaluates to a procedure value, while + would expect all its arguments to be numeric.
The rules of Scheme are that parentheses matters. x and (x) are two totally different things. The first x can be any value, but (x) is an application so x have to evaluate to a procedure. Some exceptions are for special forms you need to know by heart like cond, and define but rather than that it's very important to know you change the meaning of a program by adding parentheses.
The correct definition of your procedure might be:
(define (foo x)
(if (zero? x)
0
(+ (expt x (- x 1))
(foo (- x 1)))))
(foo 5) ; ==> 701
Here I've changed cond to if since none of conds features were used. Seeing cond I expect either side effects or more than one predicate.

Scheme "application: not a procedure;" when calculating a derivative

I am brand new to Scheme and am working on an assignment to implement stochastic gradient descent. So far I believe I have the structure of the program correct however my procedure that takes the derivative of a function f(x) is giving me some trouble. In my "try" loop at the bottom of the code I recursively call (try (func-eval guess)) where (func-eval guess) calculates the next guess of my function's local minimal with the formula *x - alpha*f'(x)* where alpha = 0.1.
I seem to be getting an error when calculating the derivative... I am using Dr.Racket IDE and it has highlighted this following line as being problematic:
(f (+ x dx)) ... which is the second line in my local derivative procedure:
(define (local-minimal first-guess)
;A way to check a guess
(define(good-enough? val1 val2)
(<(abs(- val1 val2)) 0.00001))
; x_new = x_old - alpha*f'(x) /// f(x)=(x+1)^2+2 //// alpha = 0.1
(define (func-eval x)
(- x (* 0.1((derivative (+ 2(expt (+ x 1) 2)) 0.00001)x))))
(define (derivative f dx)
(lambda (x)
(/ (- (f (+ x dx)) (f x))
dx)))
; trys the guess
(define (try guess)
(if (good-enough? guess -1)
guess
(try (func-eval guess))))
(try first-guess))
I am getting an error saying:
application: not a procedure;
expected a procedure that can be applied to arguments
given: 3
arguments...:
-1.99999
Is this a syntax error? I thought that I would be able to say f(x+dx) by using (f (+ x dx)) .... does this mean that I need to put an operator before the f in those parenthesis?
The highlighting and error message are together telling you something useful: the thing derivative is receiving as its first argument f isn't a function, which it needs to be to called in (f (+ x dx)). Where does the argument come from? We could run DrRacket's debugger, but here we can just look at the code -- the only place derivative is called from is the first line of func-eval, so that's where we must have passed a number instead of a function. Sure enough, (+ 2 (expt (+ x 1) 2)) (with x bound) is just a number, and trying to apply this gives an error.
When calling derivative, the first argument has to be a function. In the following procedure call, the expression in the first argument gets evaluated to a number, not a function:
(derivative (+ 2 (expt (+ x 1) 2)) 0.00001)
To fix it, pack the expression inside a lambda, which makes it an actual function:
(derivative (lambda (x) (+ 2 (expt (+ x 1) 2))) 0.00001)

Resources