LISP &rest issue - lisp

So I'm new to LISP, and I'm playing with a couple of basic sum functions.
(defun suma (&rest L)
(cond
((null L) 0)
(T (+ (CAR L) (EVAL (CONS 'suma (CDR L)))))
))
(defun suma2 (&rest L)
(cond
((null L) 0)
(T (+ (car L) (suma2 (cdr L))))
))
The first function works just fine. The second function gives this error: SB-KERNEL::CONTROL-STACK-EXHAUSTED.
My question is: why is the first function ok and the second is not when they are essentially doing the same thing?

If you call, say, (suma2 1 2 3), L will be the list (1 2 3). You will then call (suma2 (cdr L)), i.e. (suma2 '(2 3)). In that invocation L will be the list ((2 3)), i.e. a list containing a single element: the list (2 3). Now it will call (suma2 (cdr L)) again and this time (cdr L) is the empty list, so in the next invocation L is a list containing the empty list. Since that's still a list containing one element, it will again recurse and again and again. The case where L is empty will never be reached because L will always be a list containing exactly one element: the result of (cdr L).
So you should either change your suma2 function to accept a list instead of a variable number of arguments (and then call it as (suma2 (list 1 2 3)) or (suma2 '(1 2 3)) instead of (suma2 1 2 3)) or use apply to call suma2 with the contents of the list as its arguments instead of the list itself.

Your function call in the second function (-> suma2) is wrong.
You expect your function to be called like this:
(suma2 1 2 3 4)
But the first recursive call is equivalent to this:
(suma2 '(2 3 4))
You pass a list, where individual elements are expected. See the documentation for APPLY.

Related

Reverse the order of pairs

I am trying to write a function in Racket that will reverse the order of pairs. For example, given the list '(1 2) the function should produce '(2 1). Here is my code so far:
(define (reverse aList)
(cons (second aList)
(first aList))
This is not producing the correct answer, however. When I test with '(a b) it returns '(b . a) instead of '(b a). How do I get rid of the period between the b and a?
You should have:
(define (reverse-pair lst)
(cons (second lst) (cons (first lst) empty)))
As stated in Racket's docs:
The cons function actually accepts any two values, not just a list for the second argument. When the second argument is not empty and not itself produced by cons, the result prints in a special way. The two values joined with cons are printed between parentheses, but with a dot (i.e., a period surrounded by whitespace) in between.
So,
> (cons 1 2)
'(1 . 2)
> (cons 1 (cons 2 empty)) ; equivalent to (list 1 2)
'(1 2)

How to use foldr in Racket to eliminate numbers in a list that are greater than any subsequent numbers

I have to write a function in Racket using foldr that will take a list of numbers and remove list elements that are larger than any subsequent numbers.
Example: (eliminate-larger (list 1 2 3 5 4)) should produce (1 2 3 4)
I can do it without using foldr or any higher-order functions but I can't figure it out with foldr. Here's what I have:
(define (eliminate-larger lst)
(filter (lambda (z) (not(equal? z null)))
(foldr (lambda (x y)
(cons (determine-larger x (rest lst)) y)) null lst))
)
(define (determine-larger value lst)
(if (equal? (filter (lambda (x) (>= x value)) lst) lst)
value
null)
)
determine-larger will take in a value and a list and return that value if it is greater than or equal to all elements in the list. If not, it returns null. Now the eliminate-larger function is trying to go through the list and pass each value to determine-larger along with a list of every number after it. If it is a "good" value it will be returned and put in the list, if it's not a null is put in the list. Then at the end the nulls are being filtered out. My problem is getting the list of numbers that follow after the current number in the foldr function. Using "rest lst" doesn't work since it's not being done recursively like that. How do I get the rest of the numbers after x in foldr?
I really hope I'm not doing your homework for you, but here goes ...
How do I get the rest of the numbers after x in foldr?
Because you're consuming the list from the right, you can structure your accumulator such that "the rest of the numbers after x" are available as its memo argument.
(define (eliminate-larger lst)
(foldr
(lambda (member memo)
(if (andmap (lambda (n) (<= member n)) memo)
(cons member memo)
memo))
'()
lst))
(eliminate-larger (list 1 2 3 5 4)) ;; (1 2 3 4)
This is admittedly a naive solution, as you're forced to traverse the entire accumulator with each iteration, but you could easily maintain a max value, in addition to your memo, and compare against that each time through.
Following works:
(define (el lst)
(define (inner x lsti)
(if(empty? lsti) (list x)
(if(<= x (apply max lsti))
(cons x lsti)
lsti)))
(foldr inner '() lst))
(el (list 1 2 3 5 4))
Output:
'(1 2 3 4)
The cond version may be preferable:
(define (el lst)
(define (inner x lsti)
(cond
[(empty? lsti) (list x)]
[(<= x (apply max lsti)) (cons x lsti)]
[else lsti] ))
(foldr inner '() lst) )

LISP recursive pairing?

I'm new to LISP and I'm trying to create a recursive function that pairs the elements within a list. I'm stuck on the last part of my function with adding in the recursion.
(defun pairup (L)
(cond((null L) nil))
(list (cons (car L) (cadr L)(pairup(cdr L)))))
I know that (pairup(cdr L)))))) will show an error because its a third argument going into cons. Not sure how to add in the function again =/
INPUT: (pairup'(1 2 3 4))
OUTPUT: ((1 2) (3 4))
Here is the function:
(defun pairup (l)
(cond ((null l) nil)
((null (cdr l)) (list l))
(t (cons (list (car l) (cadr l))
(pairup (cddr l))))))
(pairup '(1 2 3 4)) ; produces ((1 2) (3 4))
(pairup '(1 2 3)) ; produces ((1 2) (3))
Note that the second branch of the cond is to terminate the recursion when only one element is left, and this is necessary if the initial list has an odd number of elements. The syntax of the cond requires that the first form of a branch be always a condition, and in the last branch the condition is t to catch all the other cases.

reversing list in Lisp

I'm trying to reverse a list in Lisp, but I get the error: " Error: Exception C0000005 [flags 0] at 20303FF3
{Offset 25 inside #}
eax 108 ebx 200925CA ecx 200 edx 2EFDD4D
esp 2EFDCC8 ebp 2EFDCE0 esi 628 edi 628 "
My code is as follows:
(defun rev (l)
(cond
((null l) '())
(T (append (rev (cdr l)) (list (car l))))))
Can anyone tell me what am I doing wrong? Thanks in advance!
Your code as written is logically correct and produces the result that you'd want it to:
CL-USER> (defun rev (l)
(cond
((null l) '())
(T (append (rev (cdr l)) (list (car l))))))
REV
CL-USER> (rev '(1 2 3 4))
(4 3 2 1)
CL-USER> (rev '())
NIL
CL-USER> (rev '(1 2))
(2 1)
That said, there are some issues with it in terms of performance. The append function produces a copy of all but its final argument. E.g., when you do (append '(1 2) '(a b) '(3 4)), you're creating a four new cons cells, whose cars are 1, 2, a, and b. The cdr of the final one is the existing list (3 4). That's because the implementation of append is something like this:
(defun append (l1 l2)
(if (null l1)
l2
(cons (first l1)
(append (rest l1)
l2))))
That's not exactly Common Lisp's append, because Common Lisp's append can take more than two arguments. It's close enough to demonstrate why all but the last list is copied, though. Now look at what that means in terms of your implementation of rev, though:
(defun rev (l)
(cond
((null l) '())
(T (append (rev (cdr l)) (list (car l))))))
This means that when you're reversing a list like (1 2 3 4), it's like you're:
(append '(4 3 2) '(1)) ; as a result of (1)
(append (append '(4 3) '(2)) '(1)) ; and so on... (2)
Now, in line (2), you're copying the list (4 3). In line one, you're copying the list (4 3 2) which includes a copy of (4 3). That is, you're copying a copy. That's a pretty wasteful use of memory.
A more common approach uses an accumulator variable and a helper function. (Note that I use endp, rest, first, and list* instead of null, cdr, car, and cons, since it makes it clearer that we're working with lists, not arbitrary cons-trees. They're pretty much the same (but there are a few differences).)
(defun rev-helper (list reversed)
"A helper function for reversing a list. Returns a new list
containing the elements of LIST in reverse order, followed by the
elements in REVERSED. (So, when REVERSED is the empty list, returns
exactly a reversed copy of LIST.)"
(if (endp list)
reversed
(rev-helper (rest list)
(list* (first list)
reversed))))
CL-USER> (rev-helper '(1 2 3) '(4 5))
(3 2 1 4 5)
CL-USER> (rev-helper '(1 2 3) '())
(3 2 1)
With this helper function, it's easy to define rev:
(defun rev (list)
"Returns a new list containing the elements of LIST in reverse
order."
(rev-helper list '()))
CL-USER> (rev '(1 2 3))
(3 2 1)
That said, rather than having an external helper function, it would probably be more common to use labels to define a local helper function:
(defun rev (list)
(labels ((rev-helper (list reversed)
#| ... |#))
(rev-helper list '())))
Or, since Common Lisp isn't guaranteed to optimize tail calls, a do loop is nice and clean here too:
(defun rev (list)
(do ((list list (rest list))
(reversed '() (list* (first list) reversed)))
((endp list) reversed)))
In ANSI Common Lisp, you can reverse a list using the reverse function (nondestructive: allocates a new list), or nreverse (rearranges the building blocks or data of the existing list to produce the reversed one).
> (reverse '(1 2 3))
(3 2 1)
Don't use nreverse on quoted list literals; it is undefined behavior and may behave in surprising ways, since it is de facto self-modifying code.
You've likely run out of stack space; this is the consequence of calling a recursive function, rev, outside of tail position. The approach to converting to a tail-recursive function involves introducing an accumulator, the variable result in the following:
(defun reving (list result)
(cond ((consp list) (reving (cdr list) (cons (car list) result)))
((null list) result)
(t (cons list result))))
You rev function then becomes:
(define rev (list) (reving list '()))
Examples:
* (reving '(1 2 3) '())
(3 2 1)
* (reving '(1 2 . 3) '())
(3 2 1)
* (reving '1 '())
(1)
If you can use the standard CL library functions like append, you should use reverse (as Kaz suggested).
Otherwise, if this is an exercise (h/w or not), you can try this:
(defun rev (l)
(labels ((r (todo)
(if todo
(multiple-value-bind (res-head res-tail) (r (cdr todo))
(if res-head
(setf (cdr res-tail) (list (car todo))
res-tail (cdr res-tail))
(setq res-head (list (car todo))
res-tail res-head))
(values res-head res-tail))
(values nil nil))))
(values (r l))))
PS. Your specific error is incomprehensible, please contact your vendor.

Converting a dotted pair to a two-element list in LISP

I am new to lisp and working on a homework problem to flatten a nested list. I have my funciton working except it needs to 'remove' dotted pairs. So given (1 (2 3) (4 . 5) ((6 7) (89))) my function should output (1 2 3 4 5 6 7 8 9).
So.. my actual question..
Given a dotted pair e.g (1 . 2), how can I get the list '(1 2)?
A cons cell is a structure that has two parts, called its car and its cdr. The pair (1 . 2) is a cons cell whose car is 1 and whose cdr is 2. Lists in Lisps are built up from cons cells and nil. How this works is described in lots of places, including the answer to Recursive range in Lisp adds a period? A list is either the empty list () (also called nil), or a cons whose car is the first element of the list and whose cdr is another list which is the rest of the list. That means that a list
(1 2)
is built of cons cells and nil as
(cons 1 (cons 2 nil))
If you've already got (1 . 2), then you can get 1 and 2 with car and cdr. You'd put them back together as just described. That is,
(let ((x '(1 . 2)))
(cons (car x) (cons (cdr x) nil)))
Alternatively, you could just use list:
(let ((x '(1 . 2)))
(list (car x) (cdr x)))
If you want to reuse the same cons cell, you could replace the cdr of the cell with (cons 2 nil). For instance (and note that we're not quoting the pair anymore, because modifying literal data is undefined behavior):
(let ((x (cons 1 2)))
(setf (cdr x) (cons (cdr x) nil))
x)
That could also be
(let ((x (cons 1 2)))
(setf (cdr x) (list (cdr x)))
x)
You could also use rplacd:
(let ((x (cons 1 2)))
(rplacd x (list (cdr x)))
x)