Lisp isn't reversing my lists - common-lisp

I'm doing some homework in Lisp, using clisp to test, and I'm loading this code and running in in clisp
(defun myreverse (thelist)
(reverse thelist)
(print thelist)
(if (equal thelist nil)
nil
(if (consp (first thelist))
(cons (myreverse (reverse (first thelist)))
(myreverse (reverse (rest thelist))))
(cons (first thelist) (myreverse (rest thelist))))))
I'm kind of new to Lisp, but this code isn't reversing thelist at all, my output is:
[18]> (myreverse '(a (b c) d))
(A (B C) D)
((B C) D)
(C B)
(B)
NIL
(D)
NIL
(A (C B) D)
The first line of my code says (reverse thelist), why isn't it reversing for the first print statement? Am I missing something?

I believe (reverse) is without side-effects, thus it doesn't reverse the original list, but returns a new, reversed one. This is not so natural in Common Lisp, but expected in Scheme. Nevertheless, here is the doc http://www.lispworks.com/documentation/HyperSpec/Body/f_revers.htm#reverse
What I think you want is (nreverse).

Related

Is the book's answer-sheet wrong about this "flatten the nested list" problem?

I am trying to learn Common Lisp with the book Common Lisp: A gentle introduction to Symbolic Computation. In addition, I am using SBCL, Emacs, and Slime.
In Chapter 8, the author presents the concept of recursion. More specifically, he shows cad/cdr recursion on trees. One of the exercises about this topic is how to flat a nested list:
The odd thing appears in the answer-sheet showing this as the correct answer:
The book's answer-sheet solution does not generate the expected result with the example provided on the question under my environment.
(defun flatten-book (tree)
(cond ((atom tree) (list tree))
(t (append (flatten-book (car tree))
(flatten-book (cdr tree))))))
It is full of NILs and it should not be. Thus, I get on my REPL:
CL-USER> (flatten-book '((A B (R)) A C (A D ((A (B)) R) A)))
(A B R NIL NIL A C A D A B NIL NIL R NIL A NIL NIL)
In order to get the expected result I need to change the approach inserting a null clause with:
(defun my-flatten (tree)
(cond ((null tree) nil)
((atom tree) (list tree))
(t (append (my-flatten (car tree))
(my-flatten (cdr tree))))))
This returns the correct answer:
CL-USER> (my-flatten '((A B (R)) A C (A D ((A (B)) R) A)))
(A B R A C A D A B R A)
So far, I am enjoying the book a lot. And it seems to be a classic among Common Lispers.
Is this an error in the book's answer-sheet? Did I miss something? Maybe a historical change? Maybe something related to a different compiler?
The book is wrong.
With this small change however, the answer from the book works again:
(defun flatten (tree)
(cond ((null tree) tree) ;; this case was forgotten by the book!
((atom tree) (list tree))
(t (append (flatten (car tree))
(flatten (cdr tree))))))

Lisp exit defun function with nil as value

I'm trying to do a recursive version of the function position called positionRec. The objective is define the position of an element in a list, and if the element is not in the list return "nil". For exemple:
(positionRec 'a '(b c d a e)) => 4
(positionRec 'a '(b c d e)) => nil
I have written:
(defun positionRec (c l)
(cond
((atom l) (return nil))
((equal c (first l)) 1)
(t (+ 1 (positionRec c (rest l)))) ) )
I don't succeed to return nil. I have an error "*** - return-from: no block named nil is currently visible"
Anyone can teach me how to do it?
Lisp is an expression language: it has only expressions an no statemends. This means that the value of a call to a function is simply the value of the last form involved in that call This is different than many languages which have both statements and expressions and where you have to explicitly litter your code with explicit returns to say what the value of a function call is.
A cond form in turn is an expression. The value of an expression like
(cond
(<test1> <test1-form1> ... <test1-formn>)
(<test2> <test1-form1> ... <test1-formn>)
...
(<testn> <testn-form1> ... <testn-formnn>))
is the <testm-formn> of the first <testm> which is true, or nil if none of them are (and as a special case, if there are no forms after a test which is true the value is the value of that test).
So in your code you just need to make sure that the last form in the test which succeeds is the value you want:
(defun positionRec (c l)
(cond
((atom l) nil)
((equal c (first l)) 1)
(t (+ 1 (positionRec c (rest l))))))
So, what use is return? Well, sometimes you really do want to say 'OK, in the middle of some complicated loop or something, and I'm done now':
(defun complicated-search (...)
(dolist (...)
(dolist (...)
(dotimes (...)
(when <found-the-interesting-thing>
(return-from complicated-search ...))))))
return itself is simply equivalent to (return-from nil ...) and various constructs wrap blocks named nil around their bodies. Two such, in fact, are dotimes and dolist, so if you want to escape from a big loop early you can do that:
(defun complicated-search (...)
(dolist (...)
(when ...
(return 3)))) ;same as (return-from nil 3)
But in general because Lisp is an expression language you need to use return / return-from much less often than you do in some other languages.
In your case, the modified function is going to fail: if you get to the ((atom l) nil) case, then it will return nil to its parent which will ... try to add 1 to that. A better approach is to keep count of where you are:
(defun position-of (c l)
(position-of-loop c l 1))
(defun position-of-loop (c l p)
(cond
((atom l) nil)
((equal c (first l)) p)
(t (position-of-loop c (rest l) (1+ p)))))
Note that this (as your original) uses 1-based indexing: zero-based would be more compatible with the rest of CL.
It would probably be idiomatic to make position-of-loop a local function:
(defun position-of (c l)
(labels ((position-of-loop (lt p)
(cond
((atom lt) nil)
((equal c (first lt)) p)
(t (position-of-loop (rest lt) (1+ p))))))
(position-of-loop l 1)))
And you could then use an iteration macro if you wanted to make it a bit more concise:
(defun position-of (c l)
(iterate position-of-loop ((lt l) (p 1))
(cond
((atom lt) nil)
((equal c (first lt)) p)
(t (position-of-loop (rest lt) (1+ p))))))
The main problem is that you're trying to deal with incommensurable values. On the one hand, you want to deak with numbers, on the other, you want to deal with the empty list. You cannot add a number to a list, but you will inherently try doing so (you have an unconditional (1+ ...) call in your default branch in your cond).
There are ways to work around that, one being to capture the value:
(cond
...
(t (let ((val (positionRec c (rest l))))
(when val ;; Here we "pun" on nil being both false and the "not found" value
(1+ val)))))
Another would be to use a method amenable to tail-recursion:
(defun positionrec (element list &optional (pos 1))
(cond ((null list) nil)
((eql element (head list)) pos)
(t (positionrec element (rest list) (1+ pos)))))
The second function can (with a sufficently smart compiler) be turned into, basically, a loop. The way it works is by passing the return value as an optional parameter.
You could build a version using return, but you would probably need to make use of labels for that to be straight-forward (if you return nil directly from the function, it still ends up in the (1+ ...), where you then have numerical incompatibility) so I would go with either "explicitly capture the value and do the comparison against nil/false" or "the version amenable to tail-call elimination" and simply pick the one you find the most readable.

Clisp : select sublists with a given length

Working on CLISP in Sublime Text.
Exp. in CLISP : less than 1 year
It's already for a while that I'm trying to solve this exercice... without success... as you might guess.
In fact I have to create a function which will modify the list and keeps only sublists which are equals or greater than the given number (watch below)
The list on which I have to work :
(setq liste '((a b) c (d) (e f) (e g x) f))
I'm supposed to find this as result :
(lenght 2 liste) => ((a b) (e f) (e g x))
liste => ((a b) (e f) (e g x))
Here my code :
(defun lenght(number liste)
(cond
((atom liste) nil)
((listp (car liste))
(rplacd liste (lenght number (cdr liste))) )
((<= (lenght number (car liste)) number)
(I don't know what to write) )
((lenght number (cdr liste))) ) )
It will be very kind if you could give me only some clue so as to let me find the good result.
Thanks guys.
Modifying the list does not make much sense, because it gets hairy at the head of the list to retain the original reference. Return a new list.
This is a filtering operation. The usual operator in Common Lisp for that is remove-if-not (or remove-if, or remove, depending on the condition). It takes a predicate that should return whether the element should be kept. In this case, it seems to be (lambda (element) (and (listp element) (>= (length element) minlength))).
(defun filter-by-min-length (minlength list)
(remove-if-not (lambda (element)
(and (listp element)
(>= (length element) minlength)))
list))
In many cases, when the condition is known at compile time, loop produces faster compiled code:
(defun filter-by-min-length (minlength list)
(loop :for element :in list
:when (and (listp element)
(>= (length element) minlength))
:collect element))
This returns a new list that fulfills the condition. You'd call it like (let ((minlength-list (filter-by-min-length 2 raw-list))) …).
Many basic courses insist on recursively using primitive operations on cons cells for teaching purposes at first.
The first attempt usually disregards the possible stack exhaustion. At each step, you first look whether you're at the end (then return nil), whether the first element should be discarded (then return the result of recursing on the rest), or if it should be kept (then cons it to the recursion result).
If tail call optimization is available, you can refactor this to use an accumulator. At each step, instead of first recursing and then consing, you cons a kept value onto the accumulator and pass it to the recursion. At the end, you do not return nil, but reverse the accumulator and return that.
Well, I have found the answer that I was looking for, after scratching my head until blood...
Seriously, here is the solution which is working (and thanks for the correction about length which helped me to find the solution ^^) :
(defun filter-by-min-length (min-length liste)
(cond
((atom liste) nil)
((and (listp (car liste))(>= (length (car liste)) min-length))
(rplacd liste (filter-by-min-length min-length (cdr liste))) )
((filter-by-min-length min-length (cdr liste))) ) )
A non-modifying version
(defun filter-by-min-length (min-length le)
(cond ((atom le) nil)
((and (listp (car le)) (>= (length (car le)) min-length))
(cons (car le) (filter-by-min-length min-length (cdr le))))
(t (filter-by-min-length min-length (cdr le)))))
Test:
(defparameter *liste* '((a b) c (d) (e f) (e g x) f))
(filter-by-min-length 2 *liste*)
;; ((A B) (E F) (E G X))
*liste*
;; ((A B) C (D) (E F) (E G X) F) ; -> *liste* not modified
For building good habits, I would recommend to use defparameter instead of setq, since the behaviour of setq might not always be defined (see here). In the link, it is said:
use defvar, defparameter, or let to introduce new variables. Use setf
and setq to mutate existing variables. Using them to introduce new
variables is undefined behaviour

Write a recursive LISP function that finds the dot product of two lists of numbers of same length

Just started to learn LISP and I'm trying to figure out how to write the following recursive function.
So should I have
(DOT-PRODUCT '(1 2) '(3 4)))
The output should be 11
I've written the following
(defun DOT-PRODUCT (a b)
(if (or (null a) (null b))
0
(+ (* (first a) (first b))
(DOT-PRODUCT (rest a) (rest b)))))
And everything seems to work; however, it still works with lists of different lengths. I want it to just work with lists of numbers that have the same length. Where should I add code that returns "invalid length" should we have such?
A simple way is to rewrite the function so that it checks different cases using the conditional form cond:
(defun dot-product (a b)
(cond ((null a) (if (null b) 0 (error "invalid length")))
((null b) (error "invalid length"))
(t (+ (* (first a) (first b))
(dot-product (rest a) (rest b))))))
In the first branch of the cond, if the first argument is NIL, the second one must be NIL as well, otherwise an error is generated. In the second branch, we already know that a is not NIL, so an error is immediately generated. Finally, the result is calculated.
Multiply corresponding elements of lists X and Y:
(mapcar #'* X Y)
Add elements of a list Z:
(reduce #'+ Z)
Put together: dot product:
(reduce #'+ (mapcar #'* X Y))
reduce and mapcar are the basis for the "MapReduce" concept, which is a generalization of that sort of thing that includes dot products, convolution integrals and a myriad ways of massaging and summarizing data.
One can increase efficiency by introducing an accumulator variable and turning the standard recursion into a tail recursion. In this example, I used (labels) to define the recursion:
(defun DOT-PRODUCT (a b)
(labels ((dp (x y accum)
(if (or (null x) (null y))
accum
(dp (rest x) (rest y) (+ accum (* (first x) (first y)))))))
(if (= (length a) (length b))
(dp a b 0)
(error "Invalid length."))))

How to make deep-reverse function in Lisp

I am trying to make deep-reverse function in lisp. For example:
(a (b c d) e) -> (e (d c b) a)
Here is my code.
(defun deeprev (l)
(cond ((null l) nil)
((list (car l)) (append (deeprev (cdr l)) (deeprev (car l))))
(t (append (deeprev (cdr l))(car l)))
)
)
Whenever I compile and load, I have an error:
Error: Attempt to take the car of E which is not listp
The easiest option would be to just REVERSE the current list, and use MAPCAR to reverse all sublist with the same function.
(defun tree-reverse (tree)
"Deep reverse TREE if it's a list. If it's an atom, return as is."
(if (listp tree)
(mapcar #'tree-reverse
(reverse tree))
tree))
(tree-reverse '(a (b c d) e)) ;=> (E (D C B) A)
In your function, you assume that if the l input variable is not nil, then it is necessarily a cons-cell, because you unconditionally takes (car l) inside the (list ...) function. That's why you have an error. There are many other things that are not nil which could be bound to l at this point, like numbers or symbols.
By the way, (list ...) just builds a list, you would need to use listp instead. Since you ruled out the nil case and a list is defined as either nil or a cons, you could have used also consp.

Resources