How can i subtract arbitrary 2 lists in racket? - racket

I want to define a function that consumes 2 lists and do subtraction resulting another list.
For example, when list1 is '(a a b b c) and list2 is '(a b), the subtraction result should be '(a b c).
I tried to implement it by lambda and remove, ended up making sevral lists.
I really have no idea how to do this.

Here is one way:
#lang racket
(define (subtract xs ys)
(if (empty? ys)
xs
(subtract (remove (first ys) xs) (rest ys))))
(subtract '(a a b b c) '(a b))

Related

A list with their position via for loop in racket

(define ( addposition x )
(cond
[(empty? x) "empty list"]
[#t (for/list ([i x])
(list i (add1 (index-of x i))))]
))
(addposition (list 'a 'b 'c ))
it returns me '((a 1) (b 2) (c 3)), but I need the list like '(a 1 b 2 c 3)
As a bare minimum to get what you want you can throw that nested list to a (flatten) call:
> (flatten '((a 1) (b 2) (c 3)))
'(a 1 b 2 c 3)
But overall the idea to build mini lists with index-of and then flattening it is not the most performant. Nor will it be correct if your list contains duplicate values.
If we keep our own record of the next index, and using recursion instead of the otherwise handy for/list structure, we can build our list this way:
(define (add-positions xs [ind 0])
(if (null? xs)
xs
(append (list (first xs) ind)
(add-positions (rest xs) (add1 ind))
)))
(add-positions '(a b c d))
;=> '(a 0 b 1 c 2 d 3)
This can be expressed pretty naturally using map and flatten:
;;; Using map and flatten:
(define (list-pos xs (start 0))
(flatten (map (lambda (x y) (list x y))
xs
(range start (+ start (length xs))))))
Here map creates a list of lists, each containing one value from the input list and one value from a range list starting from start, and flatten flattens the result.
This seems more natural to me than the equivalent using for/list, but tastes may differ:
;;; Using for/list:
(define (list-pos xs (start 0))
(flatten (for/list ((x xs)
(p (range start (+ start (length xs)))))
(list x p))))
There are a lot of ways that you could write this, but I would avoid using append in loops. This is an expensive function, and calling append repeatedly in a loop is just creating unnecessary overhead. You could do this:
;;; Using Racket default arguments and add1:
(define (list-pos xs (pos 0))
(if (null? xs)
xs
(cons (car xs)
(cons pos (list-pos (cdr xs) (add1 pos))))))
Here the first element of the list and a position counter are added onto the front of the result with every recursive call. This isn't tail recursive, so you might want to add an accumulator:
;;; Tail-recursive version using inner define:
(define (list-pos xs (start 0))
(define (loop xs pos acc)
(if (null? xs)
(reverse acc)
(loop (cdr xs)
(add1 pos)
(cons pos
(cons (car xs) acc)))))
(loop xs start '()))
Because the intermediate results are collected in an accumulator, reverse is needed to get the final result in the right order.
You could (and I would) replace the inner define with a named let. Named let should work in Racket or Scheme; here is a Scheme version. Note that Scheme does not have default arguments, so an optional argument is used for start:
;;; Tail-recursive Scheme version using named let:
(define (list-pos xs . start)
(let loop ((xs xs)
(pos (if (null? start) 0 (car start)))
(acc '()))
(if (null? xs)
(reverse acc)
(loop (cdr xs)
(add1 pos)
(cons pos
(cons (car xs) acc))))))
All of the above versions have the same behavior:
list-pos.rkt> (list-pos '(a b c))
'(a 0 b 1 c 2)
list-pos.rkt> (list-pos '(a b c) 1)
'(a 1 b 2 c 3)
Here is a simple solution using for/fold
(define (addposition l)
(for/fold ([accum empty]) ([elem l])
(append accum elem)))
I love the for loops in Racket 😌
Note: As pointed out by ad absurdum, append is expensive here. So we can simply reverse first and then use cons to accumulate
(define (addposition l)
(for/fold ([accum empty]) ([elem (reverse l)])
(cons (first elem) (cons (second elem) accum))))
As others have pointed out, you can start by making a list of lists. Let's use a list comprehension:
> (for/list ([x '(a b c)]
[pos (in-naturals 1)])
(list x pos))
'((a 1) (b 2) (c 3))
Here, we iterate in parallel over two sets of data:
The list '(a b c)
The stream (in-naturals 1), which produces 1, 2, 3, ....
We combine them into lists with list, giving this structure:
'((a 1) (b 2) (c 3))
This is called "zipping", and using list comprehensions is a convenient way to do it in Racket.
Next, we want to flatten our list, so it ends up looking like this:
'(a 1 b 2 c 3)
However, you shouldn't use flatten for this, as it flattens not just the outermost list, but any sub-lists as well. Imagine if we had data like this, with a nested list in the middle:
> (flatten
(for/list ([x '(a (b c d) e)]
[pos (in-naturals 1)])
(list x pos)))
'(a 1 b c d 2 e 3)
The nested list structure got clobbered! We don't want that. Unless we have a good reason, we should preserve the internal structure of each element in the list we're given. We'll do this by using append* instead, which flattens only the outermost list:
> (append*
(for/list ([x '(a (b c d) e)]
[pos (in-naturals 1)])
(list x pos)))
'(a 1 (b c d) 2 e 3)
Now that we've got it working, let's put it into a function:
> (define (addposition xs)
(append*
(for/list ([x xs]
[pos (in-naturals 1)])
(list x pos))))
> (addposition '(a b c))
'(a 1 b 2 c 3)
> (addposition '(a (b c d) e))
'(a 1 (b c d) 2 e 3)
Looks good!

How can I paste a element between all elements of a list?

I want to paste between every element of a lista special element. In example:
(EINFUEGEN '(A B C) '*);-> (A * B * C)
How can I implement that on the easiest way?
The fun way:
(cdr (mapcan #'list '#1=(* . #1#) '(a b c)))
The respectable way:
(loop
for (x . xs) on '(a b c)
collect x
when xs collect '*)
for <var> on <list> iterates over all sublists, meaning var will be bound to (a b c), then (b c) then (c) and finally ().
(x . xs) is a destructuring notation to bind respectively x and xs to the head and tail of each list being visited. This is necessary here to check whether there are remaining elements.
collect <val> adds <val> to implicit collection being built
when <test> <clause> executes the LOOP clause <clause> only when <test> is satisfied. Here, I test if there are more elements in the list; when it is the case, I also collect the star symbol.

Creating a custom reverse of list

I'm trying to create a custom reverse of list in Lisp. I'm pretty new to Lisp programming, and still struggling with syntax. This is my code so far
(defun new-union(l1 l2)
(setq l (union l1 l2))
(let (res)
(loop for x in l
do(setq res (cons (car l) res))
do(setq l (cdr l)))))
Here I'm taking two lists, and forming union list l. Then for reversing the list l I'm accessing element wise to append it to a new list res. Then consequently using the cons, car and cdr to update the list.
However, I'm getting a weird output. Can someone please suggest where I'm going wrong?
I'm aware of an inbuilt function for the same called nreverse , but I wanted to experiment to see how the Lisp interprets the data in list.
On printing res at the end, for example
(new-union '(a b c) '(d e f))
the output for above call gives me
(L A A A A A A A X X)
I think I'm doing the looping wrong.
Problems
(summary of previous comments)
Bad indentation, spaces, and names; prefer this:
(defun new-union (l1 l2)
(setq list (union l1 l2))
(let (reversed)
(loop for x in list
do (setq res (cons (car list) reversed))
do (setq list (cdr list)))))
Usage of SETQ on undeclared, global variables, instead of a LET
Mutation of the structure being iterated (LIST)
Not using X inside the LOOP (why define it?)
The return value is always NIL
Refactoring
(defun new-union (l1 l2)
(let ((reverse))
(dolist (elt (union l1 l2) reverse)
(push elt reverse))))
Define a local reverse variable, bound to NIL by default (you could set it to '(), this is sometimes preferred).
Use DOLIST to iterate over a list and perform side-effects; the third argument is the return value; here you can put the reverse variable where we accumulate the reversed list.
For each element elt, push it in front of reverse; if you want to avoid push for learning purposes, use (setf reverse (cons elt reverse)).
Common Lisp is multi-paradigm and favors pragmatic solutions: sometimes a loop is more natural or more efficient, and there is no reason to force yourself to adopt a functional style.
Functional implementation
However, lists provide a natural inductive structure: recursive approaches may be more appropriate in some cases.
If you wanted to use a functional style to compute reverse, be aware that tail-call optimization, though commonly available, is not required by the language specification (it depends on your implementation capabilities and compiler options).
With default settings, SBCL eliminates calls in tail positions and would eliminate the risk of stack overflows with large inputs. But there are other possible ways to obtain bad algorithmic complexities (and wasteful code) if you are not careful.
The following is what I'd use to define the combination of union and reverse; in particular, I prefer to define a local function with labels to avoid calling new-union with a dummy nil parameter. Also, I iterate the list resulting from the union only once.
(defun new-union (l1 l2)
(labels ((rev (list acc)
(etypecase list
(null acc)
(cons (rev (rest list)
(cons (first list) acc))))))
(rev (union l1 l2) nil)))
Trace
0: (NEW-UNION (A B C) (D E F))
1: (UNION (A B C) (D E F))
1: UNION returned (C B A D E F)
1: (REV (C B A D E F) NIL)
2: (REV (B A D E F) (C))
3: (REV (A D E F) (B C))
4: (REV (D E F) (A B C))
5: (REV (E F) (D A B C))
6: (REV (F) (E D A B C))
7: (REV NIL (F E D A B C))
7: REV returned (F E D A B C)
6: REV returned (F E D A B C)
5: REV returned (F E D A B C)
4: REV returned (F E D A B C)
3: REV returned (F E D A B C)
2: REV returned (F E D A B C)
1: REV returned (F E D A B C)
0: NEW-UNION returned (F E D A B C)
Remark
It is quite surprising to reverse the result of union, when the union is supposed to operate on unordered sets: the order of elements in the result do not have to reflect the ordering of list-1 or list-2 in any way. Sets are unordered collections having no duplicates; if your input lists already represent sets, as hinted by the name of the function (new-union), then it makes no sense to remove duplicates or expect the order to be meaningful.
If, instead, the input lists represents sequences of values, then the order matters; feel free to use append or concatenate in combination with remove-duplicates, but note that the latter will remove elements in front of the list by default:
(remove-duplicates (concatenate 'list '(4 5 6) '(2 3 4)))
=> (5 6 2 3 4)
You may want to use :from-end t instead.
Ok...I think you want to take two lists, combine them together, remove duplicates, and then reverse them.
Your biggest problem is that you're using loops instead of recursion. LISP was born to do list processing using recursion. It's far more natural.
Below is a very simple example of how to do that:
(defvar l1 '(a b c)) ;first list
(defvar l2 '(d e f)) ;second list
(defun my-reverse (a b) ;a and b are lists
"combines a and b into lst, removes duplicates, and reverses using recursion"
(let ((lst (remove-duplicates (append a b))))
(if (> (length lst) 0)
(append (last lst) (my-reverse nil (butlast lst)))
nil)))
Sample Run compiled in SLIME using SBCL
; compilation finished in 0:00:00.010
CL-USER> l1 ;; verify l1 variable
(A B C)
CL-USER> l2 ;; verify l2 variable
(D E F)
CL-USER> (append l1 l2) ;; append l1 and l2
(A B C D E F)
CL-USER> (my-reverse l1 l2) ;; reverse l1 and l2
(F E D C B A)

How does "Cons" work in Lisp?

I was studying Lisp and I am not experienced in Lisp programming. In a part of my studies I encountered the below examples:
> (cons ‘a ‘(a b)) ----> (A A B)
> (cons ‘(a b) ‘a) ----> ((A B).A)
I was wondering why when we have (cons ‘a ‘(a b)) the response is (A A B) and why when we change it a little and put the 'a after (a b), the response is a dotted list like ((A B).A)? What is the difference between the first code line and the second one? What is going on behind these codes?
It's pretty easy to understand if you think of them as cons-cells.
In short, a cons cell consists of exactly two values. The normal notation for this is to use the dot, e.g.:
(cons 'a 'b) ==> (A . B)
But since lists are used so often in LISP, a better notation is to drop the dot.
Lists are made by having the second element be a new cons cell, with the last ending a terminator (usually nil, or '() in Common Lisp). So these two are equal:
(cons 'a (cons 'b '())) ==> (A B)
(list 'a 'b) ==> (A B)
So (cons 'a 'b) creates a cell [a,b], and (list 'a 'b) will create [a, [b, nil]]. Notice the convention for encoding lists in cons cells: They terminate with an inner nil.
Now, if you cons 'a onto the last list, you create a new cons cell containing [[a, [b, nil]], a]. As this is not a "proper" list, i.e. it's not terminated with a nil, the way to write it out is to use the dot: (cons '(a b) 'a) ==> ((a b) . a).
If the dot wasn't printed, it would have to have been a list with the structure [[a, [b, nil]], [a, nil]].
Your example
When you do (cons 'a '(a b)) it will take the symbol 'a and the list '(a b) and put them in a new cons cell. So this will consist of [a, [a, [b, nil]]]. Since this naturally ends with an inner nil, it's written without dots.
As for (cons '(a b) 'a), now you'll get [[a, [b, nil]], a]. This does not terminate with an inner nil, and therefore the dot notation will be used.
Can we use cons to make the last example end with an inner nil? Yes, if we do
(cons '(a b) (cons 'a '())) ==> ((A B) A)
And, finally,
(list '(a b) 'a))
is equivalent to
(cons (cons (cons 'a (cons 'b '())) (cons 'a '())))
See this visualization:
CL-USER 7 > (sdraw:sdraw '(A A B))
[*|*]--->[*|*]--->[*|*]--->NIL
| | |
v v v
A A B
CL-USER 8 > (sdraw:sdraw '((A B) . A))
[*|*]--->A
|
v
[*|*]--->[*|*]--->NIL
| |
v v
A B
Also:
CL-USER 9 > (sdraw:sdraw '(A B))
[*|*]--->[*|*]--->NIL
| |
v v
A B
CL-USER 10 > (sdraw:sdraw (cons 'A '(A B)))
[*|*]--->[*|*]--->[*|*]--->NIL
| | |
v v v
A A B
CL-USER 11 > (sdraw:sdraw (cons '(A B) 'A))
[*|*]--->A
|
v
[*|*]--->[*|*]--->NIL
| |
v v
A B
A cons is a data structure that can contain two values. Eg (cons 1 2) ; ==> (1 . 2). The first part is car, the second is cdr. A cons is a list if it's cdr is either nil or a list. Thus
(1 . (2 . (3 . ()))) is a list.
When printing cons the dot is omitted when the cdr is a cons or nil. The outer parentheses of the cdr is also omitted. Thus (3 . ()) is printed (3) and (1 . (2 . (3 . ()))) is printed (1 2 3). It's the same structure, but with different visualization. A cons in the car does not have this rule.
The read function reads cons with dot and the strange exceptional print format when the cdr is a list. It will at read time behave as if it were cons.
With a special rule for both read and print the illusion of a list is complete even when it's chains of cons.
(cons ‘a ‘(a b)) ----> (A . (A B))
(cons ‘(a b) ‘a) ----> ((A B) . A)
When printing, the first is one list of 3 elements since the cdr is a list.
A list (a b c) is represented (stored internally) as three cons-cells: (cons 'a (cons 'b (cons 'c '()). Note that the last pair has '() in its cdr.
Series of cons-cells whose last cdr is '() is printed as a list by the printer. The example is thus printed as (a b c).
Let's look at: (cons 'a '(a b)).
The list '(a b) is represented as (cons 'a (cons 'b '()). This means that
(cons 'a '(a b)) produces: (cons 'a (cons 'a (cons 'b '())).
Let's look at: (cons '(a b) 'a).
The list '(a b) is represented as (cons 'a (cons 'b '()). This means that
(cons (cons '(a b) 'a)) produces (cons (cons 'a (cons 'b '()) 'a).
Note that this series does not end in '(). To show that the printer uses dot notation. ( ... . 'a) means that a value consists of a series of cons-cells and that the last cdr contains 'a. The value (cons (cons 'a (cons 'b '()) 'a) is thus printed as '((a b) . a).
cons is just a pair data type. For example, (cons 1 2) is a pair of 1 and 2, and it will be printed with the two elements seperated by a dot like (1 . 2).
Lists are internally represented as nested conses, e.g. the list (1 2 3) is (cons 1 (cons 2 (cons 3 '())).

Sublist in common lisp

I have list of lists in my program
for example
(( a b) (c d) (x y) (d u) ........)
Actually I want to add 1 new element in the list but new element would be a parent of all existing sublists.
for example if a new element is z, so my list should become like this
( (z( a b) (c d) (x y) (d u) ........))
I have tried with push new element but it list comes like this
( z( a b) (c d) (x y) (d u) ........)
that I dont want as I have lot of new elements coming in and each element represents some block of sublists in the list
Your help would highly be appreciated.
It sounds like you just need to wrap the result of push, cons, or list* in another list:
(defun add-parent (children parent)
(list (list* parent children)))
(add-parent '((a b) (c d) (x y) (d u)) 'z)
;;=> ((Z (A B) (C D) (X Y) (D U)))
This is the approach that I'd probably take with this. It's just important that you save the return value. In this regard, it's sort of like the sort function.
However, if you want to make a destructive macro out of that, you can do that too using define-modify-macro. In the following, we use define-modify-macro to define a macro add-parentf that updates its first argument to be the result of calling add-parent (defined above) with the first argument and the parent.
(define-modify-macro add-parentf (parent) add-parent)
(let ((kids (copy-tree '((a b) (c d) (x y) (d u)))))
(add-parentf kids 'z)
kids)
;;=> ((Z (A B) (C D) (X Y) (D U)))
For such a simple case you can also use a shorter backquote approach, for example:
(let ((parent 'z) (children '((a b) (c d) (e f))))
`((,parent ,#children)))
If you aren't familiar with backquote, I'd recommend reading the nice and concise description in Appendix D: Read Macros of Paul Graham's ANSI Common Lisp.