Cond statement causing slime to crash - lisp

The first part of my function is a simple cond statement. It works perfectly by itself but when the rest of the function is added it causes an unexpected error.
Problems occure when passing:
(expo 2 0)
(expo 2 1)
The function works perfectly for any other positive value of n.
(defun expo (b n)
(cond ((= n 0) 1)
((= n 1) b))
(defparameter m (* b b))
(defun expo_iter (a b)
(cond ((= a n) b)
((= (+ a 1) n) (* b (sqrt m)))
((expo_iter (+ a 2) (* b m)))))
(expo_iter 2 m)
When (expo 2 0) 'lisp connection lost unexpectedly, connection broken by remote peer.' Never had this error before, any ideas?

There are many things wrong with this function.
The initial cond is almost certainly malformed since it does nothing at all. Probably it should.
There's a missing close paren which I assume is a cut & paste error.
Don't use defparameter (or defvar, or defconstant) other than at toplevel unless you really know what you are doing. Instead use let.
Don't use defun other than at toplevel unless you really know what you are doing. Instead use labels (or flet).
the local function has an argument with the same name as one of the arguments to the the global function which is confusing (although I often do that too, this says something bad about my programs, not that it is OK).
The use of non-toplevel defun &c makes it look as if it has been translated, badly, from Scheme perhaps? The Scheme equivalent would be less atrocious but still would fail to terminate.
Then if you actually think about what the function does you will see why it fails to terminate, and will either cause a stack overflow very quickly in if tail calls are not eliminated, or will eventually die through memory exhaustion because of bignum consing if they are. Just think about what the base case of the recursion is. What should the junk cond be doing?

Related

unbound identifier in module error ( palindrome number )

I'm a noob in scheme ... I am trying to make an exercise so that it will check if a number is a palindrome or not ( I know how to do it in c, c++ and java). But I keep getting this error "c: unbound identifier in module in: c". I searched wide and far for the error, and yes there are tens of topics on it, but all on complicated stuff that have nothing to do with my punny code. My question is, can somebody please explain to me what does the error actually mean and how can I avoid it ? My code so far :
#lang racket
(define (palindrome n)
(if (> 10 n) #t
(check n)
)
)
(define (check n)
(if (> n 0)
((= c (modulo n 10))
(= x (+ (* x 10) c))
(= n (/ n 10)))
(checkp )
)
)
(define (checkp k)
(if (= k n) #t
#f)
)
The error reported occurs in the check procedure. All those references to the variables called c and x will fail, what are those variables supposed to be? where do they come from? Remember: in Scheme = is used for comparing two numbers, not for assignment.
There are other problems. The last line of check is calling checkp, but you forgot to pass the parameter. Also the syntax in the if expression is wrong, you can't write more than two conditions in it (the "consequent" and the "alternative"), if you need more than two conditions you should use cond.
Please be careful with those parentheses, you must not use them to group expressions (they're not like curly braces!). In Scheme, if you surround an expression with () it means function application, and that's not what you want to do in check.
And in the checkp procedure we have the same problem: the variable n is unbound. It's just like in any other programming language: you have to make sure that the variables come from somewhere (a parameter, a local variable, a global definition, etc.), they can't simply appear out of thin air.
UPDATE
After the update, now it's clear what you wanted to do. I'm sorry to say this, but you don't have a good grasp of even the most basic concepts of the language. All along you needed to do an iteration (typically implemented via recursion), but this is reflected nowhere in your code - you'll have to grab a good book or tutorial on Sceheme, to get the basics right. This is how the code in Java or C would look like in Scheme:
(define (check k)
(let loop ((x 0) (n k))
(if (zero? n)
(= k x)
(loop (+ (* 10 x) (remainder n 10)) (quotient n 10)))))
(define (palindrome)
(display "Enter the number: ")
(if (check (read))
(display "The number is a palindrome")
(display "The number is not a palindrome")))
Use it like this:
(palindrome)
Enter the number: 12321
The number is a palindrome

Invalid function warning with a recursive Lisp function

I'm watching these tutorials on Lisp and I've been following along so far. However, when I try to evaluate this function,
(defun tailfact (n &optional (intermediate 1))
(if (= n 1)
(return-from tailfact intermediate))
(tailfact (1 - n) (* n intermediate)))
(tailfact 5)
I get an Invalid function warning (I'm running this in Emacs). Not sure what to make of it, or how to fix it.
You accidentally wrote a space within the 1- (which is a function for subtracting 1 from the given number). Remove that space (that is, use (1- n) instead of (1 - n)) and try again.
Also, Emacs Lisp doesn't have return-from. Just say intermediate instead of (return-from tailfact intermediate). You do have to move the tailfact call within the if expression though, as the else clause.
Oh, in my testing, I found another point of difference between Common Lisp and Emacs Lisp: the latter doesn't support a default value for optional arguments, and it always uses nil. So here's one way to port your code to elisp:
(defun tailfact (n &optional intermediate)
(let ((intermediate (or intermediate 1)))
(if (= n 1)
intermediate
(tailfact (1- n) (* n intermediate)))))
However, let me be the first to agree with Rainer's comment. If you're learning from Common Lisp resources, you really should be using a Common Lisp implementation. I've heard that SLIME is an awesome Emacs mode for integrating with major CL implementations, including SBCL (which is probably one of the most commonly-used CL implementations).

Scheme - my gcd() always returns zero

I just start to learn Scheme today.
I wrote a function gcd(), but it always returns 0.
(define (gcd a b)
(cond (= b 0)
(a)
(else ((gcd b (modulo a b))))
)
)
Why I am wrong?
This should fix the problems:
(define (gcd a b)
(cond [(= b 0) a]
[else (gcd b (modulo a b))]))
You were incorrectly surrounding some expressions between parenthesis, and some parenthesis were missing from the cond expression.
Notice that in Scheme, when you surround something in parenthesis, say (a) you're telling the interpreter: a is a procedure with no arguments and I want to call it, and this was not the case in here, a is just a number.
Also, for readability's sake, it's a good idea to use [] instead of () to separate each of the conditions in a cond expression, as shown in my code above - but don't forget them, they're mandatory and in your code you forgot them in the first condition.
Other people have described what your mistake is and what you should do.
It is also instructive to consider how your code is actually run and why it produces the output you see. Because of your missing parentheses, the first case for your cond is (= b 0). The first thing (=) is taken as the condition. Everything in Scheme except #f is true, so this is always true. Since it is true, this case is evaluated. Specifically, the rest of the things in the parentheses is taken as (possible multiple) expressions to evaluate, as an implicit begin. So basically it evaluates (begin b 0). The result is the result of the last expression, 0.

scheme continuations for dummies

For the life of me, I can't understand continuations. I think the problem stems from the fact that I don't understand is what they are for. All the examples that I've found in books or online are very trivial. They make me wonder, why anyone would even want continuations?
Here's a typical impractical example, from TSPL, which I believe is quite recognized book on the subject. In english, they describe the continuation as "what to do" with the result of a computation. OK, that's sort of understandable.
Then, the second example given:
(call/cc
(lambda (k)
(* 5 (k 4)))) => 4
How does this make any sense?? k isn't even defined! How can this code be evaluated, when (k 4) can't even be computed? Not to mention, how does call/cc know to rip out the argument 4 to the inner most expression and return it? What happens to (* 5 .. ?? If this outermost expression is discarded, why even write it?
Then, a "less" trivial example stated is how to use call/cc to provide a nonlocal exit from a recursion. That sounds like flow control directive, ie like break/return in an imperative language, and not a computation.
And what is the purpose of going through these motions? If somebody needs the result of computation, why not just store it and recall later, as needed.
Forget about call/cc for a moment. Every expression/statement, in any programming language, has a continuation - which is, what you do with the result. In C, for example,
x = (1 + (2 * 3));
printf ("Done");
has the continuation of the math assignment being printf(...); the continuation of (2 * 3) is 'add 1; assign to x; printf(...)'. Conceptually the continuation is there whether or not you have access to it. Think for a moment what information you need for the continuation - the information is 1) the heap memory state (in general), 2) the stack, 3) any registers and 4) the program counter.
So continuations exist but usually they are only implicit and can't be accessed.
In Scheme, and a few other languages, you have access to the continuation. Essentially, behind your back, the compiler+runtime bundles up all the information needed for a continuation, stores it (generally in the heap) and gives you a handle to it. The handle you get is the function 'k' - if you call that function you will continue exactly after the call/cc point. Importantly, you can call that function multiple times and you will always continue after the call/cc point.
Let's look at some examples:
> (+ 2 (call/cc (lambda (cont) 3)))
5
In the above, the result of call/cc is the result of the lambda which is 3. The continuation wasn't invoked.
Now let's invoke the continuation:
> (+ 2 (call/cc (lambda (cont) (cont 10) 3)))
12
By invoking the continuation we skip anything after the invocation and continue right at the call/cc point. With (cont 10) the continuation returns 10 which is added to 2 for 12.
Now let's save the continuation.
> (define add-2 #f)
> (+ 2 (call/cc (lambda (cont) (set! add-2 cont) 3)))
5
> (add-2 10)
12
> (add-2 100)
102
By saving the continuation we can use it as we please to 'jump back to' whatever computation followed the call/cc point.
Often continuations are used for a non-local exit. Think of a function that is going to return a list unless there is some problem at which point '() will be returned.
(define (hairy-list-function list)
(call/cc
(lambda (cont)
;; process the list ...
(when (a-problem-arises? ...)
(cont '()))
;; continue processing the list ...
value-to-return)))
Here is text from my class notes: http://tmp.barzilay.org/cont.txt. It is based on a number of sources, and is much extended. It has motivations, basic explanations, more advanced explanations for how it's done, and a good number of examples that go from simple to advanced, and even some quick discussion of delimited continuations.
(I tried to play with putting the whole text here, but as I expected, 120k of text is not something that makes SO happy.
TL;DR: continuations are just captured GOTOs, with values, more or less.
The exampe you ask about,
(call/cc
(lambda (k)
;;;;;;;;;;;;;;;;
(* 5 (k 4)) ;; body of code
;;;;;;;;;;;;;;;;
)) => 4
can be approximately translated into e.g. Common Lisp, as
(prog (k retval)
(setq k (lambda (x) ;; capture the current continuation:
(setq retval x) ;; set! the return value
(go EXIT))) ;; and jump to exit point
(setq retval ;; get the value of the last expression,
(progn ;; as usual, in the
;;;;;;;;;;;;;;;;
(* 5 (funcall k 4)) ;; body of code
;;;;;;;;;;;;;;;;
))
EXIT ;; the goto label
(return retval))
This is just an illustration; in Common Lisp we can't jump back into the PROG tagbody after we've exited it the first time. But in Scheme, with real continuations, we can. If we set some global variable inside the body of function called by call/cc, say (setq qq k), in Scheme we can call it at any later time, from anywhere, re-entering into the same context (e.g. (qq 42)).
The point is, the body of call/cc form may contain an if or a condexpression. It can call the continuation only in some cases, and in others return normally, evaluating all expressions in the body of code and returning the last one's value, as usual. There can be deep recursion going on there. By calling the captured continuation an immediate exit is achieved.
So we see here that k is defined. It is defined by the call/cc call. When (call/cc g) is called, it calls its argument with the current continuation: (g the-current-continuation). the current-continuation is an "escape procedure" pointing at the return point of the call/cc form. To call it means to supply a value as if it were returned by the call/cc form itself.
So the above results in
((lambda(k) (* 5 (k 4))) the-current-continuation) ==>
(* 5 (the-current-continuation 4)) ==>
; to call the-current-continuation means to return the value from
; the call/cc form, so, jump to the return point, and return the value:
4
I won't try to explain all the places where continuations can be useful, but I hope that I can give brief examples of main place where I have found continuations useful in my own experience. Rather than speaking about Scheme's call/cc, I'd focus attention on continuation passing style. In some programming languages, variables can be dynamically scoped, and in languages without dynamically scoped, boilerplate with global variables (assuming that there are no issues of multi-threaded code, etc.) can be used. For instance, suppose there is a list of currently active logging streams, *logging-streams*, and that we want to call function in a dynamic environment where *logging-streams* is augmented with logging-stream-x. In Common Lisp we can do
(let ((*logging-streams* (cons logging-stream-x *logging-streams*)))
(function))
If we don't have dynamically scoped variables, as in Scheme, we can still do
(let ((old-streams *logging-streams*))
(set! *logging-streams* (cons logging-stream-x *logging-streams*)
(let ((result (function)))
(set! *logging-streams* old-streams)
result))
Now lets assume that we're actually given a cons-tree whose non-nil leaves are logging-streams, all of which should be in *logging-streams* when function is called. We've got two options:
We can flatten the tree, collect all the logging streams, extend *logging-streams*, and then call function.
We can, using continuation passing style, traverse the tree, gradually extending *logging-streams*, finally calling function when there is no more tree to traverse.
Option 2 looks something like
(defparameter *logging-streams* '())
(defun extend-streams (stream-tree continuation)
(cond
;; a null leaf
((null stream-tree)
(funcall continuation))
;; a non-null leaf
((atom stream-tree)
(let ((*logging-streams* (cons stream-tree *logging-streams*)))
(funcall continuation)))
;; a cons cell
(t
(extend-streams (car stream-tree)
#'(lambda ()
(extend-streams (cdr stream-tree)
continuation))))))
With this definition, we have
CL-USER> (extend-streams
'((a b) (c (d e)))
#'(lambda ()
(print *logging-streams*)))
=> (E D C B A)
Now, was there anything useful about this? In this case, probably not. Some minor benefits might be that extend-streams is tail-recursive, so we don't have a lot of stack usage, though the intermediate closures make up for it in heap space. We do have the fact that the eventual continuation is executed in the dynamic scope of any intermediate stuff that extend-streams set up. In this case, that's not all that important, but in other cases it can be.
Being able to abstract away some of the control flow, and to have non-local exits, or to be able to pick up a computation somewhere from a while back, can be very handy. This can be useful in backtracking search, for instance. Here's a continuation passing style propositional calculus solver for formulas where a formula is a symbol (a propositional literal), or a list of the form (not formula), (and left right), or (or left right).
(defun fail ()
'(() () fail))
(defun satisfy (formula
&optional
(positives '())
(negatives '())
(succeed #'(lambda (ps ns retry) `(,ps ,ns ,retry)))
(retry 'fail))
;; succeed is a function of three arguments: a list of positive literals,
;; a list of negative literals. retry is a function of zero
;; arguments, and is used to `try again` from the last place that a
;; choice was made.
(if (symbolp formula)
(if (member formula negatives)
(funcall retry)
(funcall succeed (adjoin formula positives) negatives retry))
(destructuring-bind (op left &optional right) formula
(case op
((not)
(satisfy left negatives positives
#'(lambda (negatives positives retry)
(funcall succeed positives negatives retry))
retry))
((and)
(satisfy left positives negatives
#'(lambda (positives negatives retry)
(satisfy right positives negatives succeed retry))
retry))
((or)
(satisfy left positives negatives
succeed
#'(lambda ()
(satisfy right positives negatives
succeed retry))))))))
If a satisfying assignment is found, then succeed is called with three arguments: the list of positive literals, the list of negative literals, and function that can retry the search (i.e., attempt to find another solution). For instance:
CL-USER> (satisfy '(and p (not p)))
(NIL NIL FAIL)
CL-USER> (satisfy '(or p q))
((P) NIL #<CLOSURE (LAMBDA #) {1002B99469}>)
CL-USER> (satisfy '(and (or p q) (and (not p) r)))
((R Q) (P) FAIL)
The second case is interesting, in that the third result is not FAIL, but some callable function that will try to find another solution. In this case, we can see that (or p q) is satisfiable by making either p or q true:
CL-USER> (destructuring-bind (ps ns retry) (satisfy '(or p q))
(declare (ignore ps ns))
(funcall retry))
((Q) NIL FAIL)
That would have been very difficult to do if we weren't using a continuation passing style where we can save the alternative flow and come back to it later. Using this, we can do some clever things, like collect all the satisfying assignments:
(defun satisfy-all (formula &aux (assignments '()) retry)
(setf retry #'(lambda ()
(satisfy formula '() '()
#'(lambda (ps ns new-retry)
(push (list ps ns) assignments)
(setf retry new-retry))
'fail)))
(loop while (not (eq retry 'fail))
do (funcall retry)
finally (return assignments)))
CL-USER> (satisfy-all '(or p (or (and q (not r)) (or r s))))
(((S) NIL) ; make S true
((R) NIL) ; make R true
((Q) (R)) ; make Q true and R false
((P) NIL)) ; make P true
We could change the loop a bit and get just n assignments, up to some n, or variations on that theme. Often times continuation passing style is not needed, or can make code hard to maintain and understand, but in the cases where it is useful, it can make some otherwise very difficult things fairly easy.

Standard way for breaking out of recursion in scheme

I am writing my first program in scheme. I get pretty deep into recursion because I basically interpret a program for a simple robot which can have nested procedure calls.
If I find a violation I need to stop interpreting the program and return the last valid state.
I've solved it by declaring a global variable (define illegalMoveFlag 0) and then setting it via set!.
It works fine, but I guess my tutor won't like it (because it's not functional approach I guess)
Other approach I've thought about is to add an error parameter to every function I call recursively in the program. I don't quite like it because it would make my code far less readable, but I guess it's more 'functional'.
Is there maybe a third way I didn't think about? And can my approach be justified in this paradigm, or is it basically a code smell?
Since this was your first Scheme program, you probably just need to introduce a conditional expression, cond, in order to avoid further recursion when you reach the end. For example:
; sum : natural -> natural
; compute the sum 0+1+...+max
(define (sum max)
(define (sum-helper i sum-so-far)
(if (> i max)
sum-so-far
(sum-helper (+ i 1) (+ sum-so-far i))))
(sum-helper 0 0))
(display (sum 10))
(newline)
However, if you need a traditional return to return like longjmp in C, you will need to store and use an escape continuation. This can be done like this:
(define (example)
(let/ec return
(define (loop n)
(if (= n 100000)
(return (list "final count: " n))
(loop (+ n 1))))
(loop 0)))
(display (example))
If let/ec is not defined in your Scheme implementation, then prefix your program with:
(define-syntax let/ec
(syntax-rules ()
[(_ return body ...)
(call-with-current-continuation
(lambda (return)
body ...))]))
UPDATE:
Note that cond has an => variant:
(cond
[(call-that-can-fail)
=> (lambda (a) <use-a-here>))]
[else <do-something-else>])
If the call succeeds then the first, clause is
taken and the result is bound to a. If the call fails,
then the else clause is used.
The usual way to stop recursing is, well, to stop recursing. i.e., don't call the recursive function any longer. :-)
If that is too hard to do, the other way to break out of something is to capture a continuation at the top level (before you start recursing), then invoke the continuation when you need to "escape". Your instructor may not like this approach, though. ;-)
You might want to use the built-in procedure error, like so:
(error "Illegal move") ; gives ** Error: Illegal move
This will raise an exception and stop interpreting the program (though I suspect this may not be what you are looking for).
You can also provide additional arguments, like this:
(error "Illegal move: " move) ; gives ** Error: Illegal move: <move>
You can exit of a recursion (or from any other process) using a continuation. Without knowing more specifics, I'd recommend you take a look at the documentation of your interpreter.
Make illegalMoveFlag a paramter in the function instead of a global variable
I'll give you a simple example with factorials
ie:
0! = 1
n! = n * (n - 1)! when n (1 ... infinity)
lets call this a recursive factorial
(define (fact-r n)
(if
[eq? n 0]
1
(* n (fact-r (- n 1)))
)
)
An alternative would be to use a parameter to the function to end the recursion
Lets call it iterative factorial
(define (fact-i n total)
(if
(eq? n 0)
total
(fact-i (- n 1) (* n total))
)
)
total needs to start at 1 so we should make another function to make using it nicer
(define (nice-fact n)
(fact-i n 1))
You could do something similar with illegalMoveFlag to avoid having a global variable
As far as avoiding using set! goes, we'll probably need more information.
In some cases its still rather hard to avoid using it. Scheme is fully turing complete without the use of set! however when it comes to accessing an external source of information such as a database or a robot set! can become the only practical solution...