Reverse a list with dolist in LISP - lisp

I try to reverse a list, i can't use the function "nreverse"
I try :
(defun dolist-reverse (l)
(let ((new-list (make-list (length l))))
(dolist (x l new-list)
(setf new-list (cons x new-list)))))
But the result is :
CL-USER> (dolist-reverse '(1 2 3))
(3 2 1 NIL NIL NIL)
How can i do ? (i need to use dolist)
EDIT :
Finally fix my problem :
(defun dolist-reverse (l)
(let ((new-list))
(dolist (x l new-list)
(setf new-list (cons x new-list)))))

CL-USER 11 > (defun dolist-reverse (list &aux (reverse-list nil))
(dolist (element list reverse-list)
(push element reverse-list)))
DOLIST-REVERSE
CL-USER 12 > (dolist-reverse '(1 2 3))
(3 2 1)

This one makes same thing, without changing argument to the procedure;
(defun my-reverse (l)
(if (null l) nil
(append
(my-reverse (cdr l))
(list (car l)))))

Related

Issue with extra nils in quicksort result

I'm new to lisp, and am writing code for quicksort. I am almost done, although the output is giving me some trouble. This is currently what I have:
(defun fil(P L)
(if (null L) nil
(if (funcall P (first L)) (cons (first L) (fil P (rest L)))
(fil P (rest L)))))
(defun qs(L)
(if (null L) nil
(let ((x (first L))
(gt (fil (lambda (x) (<= (first L) x))(rest L) ))
(lt (fil (lambda (x) (> (first L) x))(rest L))))
(cons (cons (qs lt) (first L)) (qs gt)))))
(write (qs '(4 2 3 1 7 3 5 3 6)))
This works, but the output looks like this:
((((((NIL . 1)) . 2) (NIL . 3) (NIL . 3) (NIL . 3)) . 4)
(((NIL . 5) (NIL . 6)) . 7))
I am not sure where the extra nils and periods and parentheses are coming from or how to fix it. Any advice is appreciated.
Look at
(cons '(a b c d) 'e)
Above code does not append E to the list.
CL-USER 4 > (cons '(a b c d) 'e)
((A B C D) . E)
It creates a new cons cell (a two element container) with the first arg and the second arg with its elements.
What you need, is to APPEND lists into a result list.
Adding to what #RainerJoswig said:
(defun %filter (pred l)
(cond ((null l) nil)
((funcall pred (car l)) (cons (car l) (%filter pred (cdr l))))
(t (%filter pred (cdr l)))))
(defun quicksort (l)
(cond ((null l) nil)
(t (let ((greater-than (%filter (lambda (x) (<= (car l) x)) (cdr l)))
(less-than (%filter (lambda (x) (> (car l) x)) (cdr l))))
(append (quicksort less-than) (list (car l)) (quicksort greater-than))))))
(quicksort '(4 2 3 1 7 3 5 3 6))
;; (1 2 3 3 3 4 5 6 7)
Alternatively also:
(defun %filter (pred l)
(mapcan (lambda (x) (if (funcall pred x) (list x) nil)) l))
(defun quicksort (l)
(cond ((null l) nil)
(t (append (quicksort (%filter (lambda (x) (< x (car l))) (cdr l)))
(list (car l))
(quicksort (%filter (lambda (x) (<= (car l) x)) (cdr l)))))))

checking if list is all numbers in lisp

so I have a program:
(defun add (L)
(cond((endp L) nil)
(t(cons(1+(first L)))(add(rest L)))))
that will add 1 to each member of the list. I want to check if the list is all numbers and return nil if not, and don't know how to go about doing that within the defun.
I thought of doing
(defun add (L)
(cond((endp L) nil)
((not(numberp(first L))) nil)
(t(cons(1+(first L)))(add(rest L)))))
but that will still return the beginning of the list if the non number is in the middle. How would I pre check and return nil at the beginning?
You can wrap it in a condition-case
(defun add (L)
(condition-case nil
(mapcar '1+ L)
(error nil)))
Another possibility is to use iteration:
(defun add (l)
(loop for x in l
if (numberp x)
collect (1+ x)
else do (return-from add nil)))
The function is immediately exited with nil on the first non numeric element.
You would not implement iteration using recursion, since Lisp already provides iteration constructs. Example: MAPCAR.
Common Lisp also provides control flow constructs like RETURN-FROM, where you return from a block. A function defined by DEFUN has a block with its name and BLOCK can also create a named block explicitly. Examples for both:
CL-USER 62 > (block mapping
(mapcar (lambda (item)
(if (numberp item)
(1+ item)
(return-from mapping nil)))
'(1 2 3 nil 5 6)))
NIL
CL-USER 63 > (block mapping
(mapcar (lambda (item)
(if (numberp item)
(1+ item)
(return-from mapping nil)))
'(1 2 3 4 5 6)))
(2 3 4 5 6 7)
As function:
CL-USER 64 > (defun increment-list (list)
(mapcar (lambda (item)
(if (numberp item)
(1+ item)
(return-from increment-list nil)))
list))
INCREMENT-LIST
CL-USER 65 > (increment-list '(1 2 3 4 5 6))
(2 3 4 5 6 7)
CL-USER 66 > (increment-list '(1 2 3 nil 5 6))
NIL
I'd say that an idiomatic way, in Common Lisp, of checking that all elements in a list are numbers would be (every #'numberp the-list), so I would probably write this as:
(defun add-1 (list)
(when (every #'numberp list)
(mapcar #'1+ list)))
It would be possible to use (if ...) or (and ...), but in this case I would argue that (when ...) makes for the clearest code.
The difficulty is that propagating nil results in the nil at the end of the list causing everything to be nil. One solution is to check that add returns nil but (rest xs) is not nil. However, IMO it is more straightforward to just iterate over the list twice, checking for numbers the first time and then doing the addition on the second iteration.
Try this:
(defun add (xs)
(cond ((endp xs) nil)
((not (numberp (car xs))) nil)
(t (let ((r (add (rest xs))))
(cond ((and (not r) (rest xs)) nil)
(t (cons (1+ (first xs)) r)))))))
Barring mistakes on my end, this results in:
(add '()) => nil
(add '(1 2)) => '(2 3)
(add '(x y)) => nil
(add '(1 2 y)) => nil
EDIT: Without let. This results in 2^(n+1)-1 calls to add for a list of length n.
(defun add (xs)
(cond ((endp xs) nil)
((not (numberp (car xs))) nil)
(t (cond ((and (not (add (rest xs))) (rest xs)) nil)
(t (cons (1+ (first xs)) (add (rest xs)))))))))

racket postfix to prefix

I have a series of expressions to convert from postfix to prefix and I thought that I would try to write a program to do it for me in DrRacket. I am getting stuck with some of the more complex ones such as (10 (1 2 3 +) ^).
I have the very simple case down for (1 2 \*) → (\* 1 2). I have set these expressions up as a list and I know that you have to use cdr/car and recursion to do it but that is where I get stuck.
My inputs will be something along the lines of '(1 2 +).
I have for simple things such as '(1 2 +):
(define ans '())
(define (post-pre lst)
(set! ans (list (last lst) (first lst) (second lst))))
For the more complex stuff I have this (which fails to work correctly):
(define ans '())
(define (post-pre-comp lst)
(cond [(pair? (car lst)) (post-pre-comp (car lst))]
[(pair? (cdr lst)) (post-pre-comp (cdr lst))]
[else (set! ans (list (last lst) (first lst) (second lst)))]))
Obviously I am getting tripped up because (cdr lst) will return a pair most of the time. I'm guessing my structure of the else statement is wrong and I need it to be cons instead of list, but I'm not sure how to get that to work properly in this case.
Were you thinking of something like this?
(define (pp sxp)
(cond
((null? sxp) sxp)
((list? sxp) (let-values (((args op) (split-at-right sxp 1)))
(cons (car op) (map pp args))))
(else sxp)))
then
> (pp '(1 2 *))
'(* 1 2)
> (pp '(10 (1 2 3 +) ^))
'(^ 10 (+ 1 2 3))
Try something like this:
(define (postfix->prefix expr)
(cond
[(and (list? expr) (not (null? expr)))
(define op (last expr))
(define args (drop-right expr 1))
(cons op (map postfix->prefix args))]
[else expr]))
This operates on the structure recursively by using map to call itself on the arguments to each call.

Quicksort in LISP

I am trying to do a quicksort using LISP but I am having trouble with my functions output.
(defun qsort (L)
(cond
((null L) nil)
(t(append
(qsort (list< (car L) (cdr L)))
(cons (car L) nil)
(qsort (list>= (car L) (cdr L)))))))
(defun list< (a b)
(cond
(( or(null a)(null b) nil))
(( < a (car b)) (list< a (cdr b)))
(t(cons (car b) (list< a (cdr b))))))
(defun list>= (a b)
(cond
(( or( null a)(null b) nil))
(( >= a (car b)) (list> a (cdr b)))
(t(cons (car b) (list> a (cdr b))))))
My problem being when list< and list>= finish the list always ends with a .T. For instance:
> (list< '4 '(1 5 3 8 2))
Entering: LIST<, Argument list: (4 (1 5 3 8 2))
Entering: LIST<, Argument list: (4 (5 3 8 2))
Entering: LIST<, Argument list: (4 (3 8 2))
Entering: LIST<, Argument list: (4 (8 2))
Entering: LIST<, Argument list: (4 (2))
Entering: LIST<, Argument list: (4 NIL)
Exiting: LIST<, Value: T
Exiting: LIST<, Value: (2 . T)
Exiting: LIST<, Value: (2 . T)
Exiting: LIST<, Value: (3 2 . T)
Exiting: LIST<, Value: (3 2 . T)
Exiting: LIST<, Value: (1 3 2 . T)
(1 3 2 . T)
Why is (4 NIL) evaluating as T?
Your problem with list<, and also with list>=, lies on ((or ( null a)(null b) nil)), it should be (( or( null a)(null b)) nil). Note nil was moved outside of the condition to be the returned value.
Furthermore, on the definition of list>= you are calling list>, but I'm positive you meant list>= instead.
I would also suggest some indentation to address the legibility of lisp, like follows
(defun qsort (L)
(cond
((null L) nil)
(t
(append
(qsort (list< (car L) (cdr L)))
(cons (car L) nil)
(qsort (list>= (car L) (cdr L)))))))
(defun list< (a b)
(cond
((or (null a) (null b)) nil)
((< a (car b)) (list< a (cdr b)))
(t (cons (car b) (list< a (cdr b))))))
(defun list>= (a b)
(cond
((or (null a) (null b)) nil)
((>= a (car b)) (list>= a (cdr b)))
(t (cons (car b) (list>= a (cdr b))))))
Some testing follows:
(list< '4 '(1 5 3 8 2))
=> (1 3 2)
(list>= '4 '(1 5 3 8 2))
=> (5 8)
(qsort '(1 5 3 8 2))
=> (1 2 3 5 8)
Lisp has different kinds of collections. I think sort a list using quick-sort is not a good choice. In the implementation of STL in C++, the sorting method of list is merge-sort. I have tried to implement a 3-way quick-sort using the collections of array.
(defun quick-sort (arr start end)
"Quick sort body"
(if (< start end)
(let ((n-pair (partition arr start end)))
(quick-sort arr start (car n-pair))
(quick-sort arr (cdr n-pair) end))
))
(defun partition (arr start end)
"Partition according to pivot."
(let ((pivot (aref arr start)) (cur start))
(loop while (<= start end) do
(cond
((< pivot (aref arr start)) ; pivot < arr[start], swap with arr[end]
(swap arr start end) (decf end))
((> pivot (aref arr start)) ; pivot > arr[start], swap with arr[start]
(swap arr cur start) (incf cur) (incf start))
(t ; otherwise
(incf start))))
(cons (decf cur) start)))
(defun swap (arr i j)
"Swap element of arr"
(let ((tmp (aref arr i)))
(setf (aref arr i) (aref arr j))
(setf (aref arr j) tmp)))
(defun quick (list)
(when (< = (length list) 1) (return-from quick list))
(let ((pivot (car list)) (rest (cdr list)) (less nil) (greater nil))
(loop for i in rest do
(if (< i pivot) (push i less) (push i greater)))
(append (quick less) (list pivot) (quick greater))))
I'd recommend to change the code of liya babu/Will Ness like this:
(defun quick (list)
(if (null list) nil
(let ((pivot (first list)) (less nil) (greater nil))
(dolist (i (rest list))
(if (< i pivot) (push i less) (push i greater)))
(append (quick less) (list pivot) (quick greater)))))
Although just slightly edited I find it both more lispy and more succinct.
There are some errors in the program. The corrected program is:
(defun qsort (L)
(cond
((null L) nil)
(t (append
(qsort (list< (car L) (cdr L)))
(cons (car L) nil)
(qsort (list>= (car L) (cdr L)))))))
(defun list< (a b)
(cond
(( or (null a) (null b)) nil)
(( < a (car b)) (list< a (cdr b)))
(t (cons (car b) (list< a (cdr b))))))
(defun list>= (a b)
(cond
(( or ( null a)(null b)) nil)
(( >= a (car b)) (list>= a (cdr b)))
(t (cons (car b) (list>= a (cdr b))))))
This should also work:
(defun qsort (l)
(cond
((null l) nil)
(t (append
(qsort (car(list<> (car l)(cdr l))))
(cons (car l) nil)
(qsort (cadr(list<> (car l)(cdr l))))))))
(defun list<> (a b &optional rl rr)
(cond
((null b) (list rl rr))
((<=(car b)a) (list<> a (cdr b) (cons (car b) rl) rr))
(t (list<> a (cdr b)rl (cons (car b) rr)))))
(setq l (loop for j from 1 to 20 append (list(random 100))))
(qsort l)
;=> (86 99 9 31 66 58 57 43 48 21 51 0 32 69 39 47 59 76 69 23)
;=> (0 9 21 23 31 32 39 43 47 48 51 57 58 59 66 69 69 76 86 99)

Setting up a equal function in common lisp using only "eq"

I've given the assingment to write a function in common lisp to compare two lists to see if they are equal and I have been bared from using the "equal" predicate I can only use "eq" and I seem to come to a wall. I get this error with my code EVAL: variable SETF has no value
The following restarts are available:
and he code:
(defun check(L1 L2)
(cond
((eq L nil) nil)
(setq x (first L1))
(setq y (first L2))
(setf L1 (rest L1))
(setf L2 (rest L2))
(if (eq x y) (check L1 L2))))
(defun b(L1 L2)
(cond
((eq L1 nil) nil)
(setf x (first L1))
(setf y (first L2))
(setf L1 (rest L1))
(setf L2 (rest L2))
(if (and (list x) (list y)
(check(x y))
(if (eq x y) (b(L1 L2))))))
I guess this is what you are looking for:
(defun compare-lists (list1 list2)
(if (and (not (null list1))
(not (null list2)))
(let ((a (car list1)) (b (car list2)))
(cond ((and (listp a) (listp b))
(and (compare-lists a b)
(compare-lists (cdr list1) (cdr list2))))
(t
(and (eq a b)
(compare-lists (cdr list1) (cdr list2))))))
(= (length list1) (length list2))))
Tests:
? (compare-lists '(1 2 3) '(1 2 3))
T
? (compare-lists '(1 2 3) '(1 2 3 4))
NIL
? (compare-lists '(1 2 3) '(1 2 (3)))
NIL
? (compare-lists '(1 2 (3)) '(1 2 (3)))
T
? (compare-lists '(1 2 (a b c r)) '(1 2 (a b c (r))))
NIL
? (compare-lists '(1 2 (a b c (r))) '(1 2 (a b c (r))))
T