I want to give a number and return the element of this position.
List lab = (R K K K K) and I want to know if something like this (position 1 lab) exists on lisp. Like in C return lab[1].
In Common Lisp the operator that gets the n-th element of a list is called nth (see the manual):
(nth 2 '(a b c d)) ; returns C
A related operator is nthcdr that returns the rest of the list starting from the n-th element:
(nthcdr 2 '(a b c d)) ; returns (C D)
For an operator that works on vectors and proper lists, see elt.
(let ((list (list 'a 'b 'c 'd)))
(prog1 list
(setf (elt list 1) 1)))
=> (A 1 C D)
Related
So I have a problem I'm trying to solve.
Write a function called parity that takes four numbers, where each
number is either 0 or 1, and produces another number that is either 0 or 1. Your function should produce 1 if there are an odd number
of ones in the input numbers and 0 if there are an even number of ones.
I'm trying to do this in a roundabout way using the map function, currently sitting at
(define (parity a b c d)
(map (lambda (thing)
(positive? thing))
'(a b c d)))
Then I would like to somehow create a new list using only the positive numbers, then find the length, then equate that to a 0 or a 1. However, my code doesn't work after I define it due to the positive? searching for a number and finding an a.
First error is already mentioned in comments- instead of '(a b c d), use (list a b c d) to get values of symbols.
There are two ways to get desired output and you don't need map in any of them:
I can follow your process of thinking and use exactly these functions:
create a new list using only the positive numbers -> filter
then find the length -> length
then equate that to a 0 or a 1. -> odd?/even? length or modulo
(define (parity a b c d)
(let* ((only-positive (filter positive? (list a b c d)))
(len (length only-positive)))
(if (odd? len) 1 0)))
This can be shortened to
(define (parity a b c d)
(if (odd? (length (filter positive? (list a b c d)))) 1 0))
And note, that problem description almost exactly matches this solution: if (odd (number of (ones in the input numbers))) 1 0.
Shorter solution with apply:
(define (parity a b c d)
(modulo (apply + (list a b c d)) 2))
I'm trying to make a for loop that iterates over a list of numbers and prints out every 3rd number.
Edit: I've only figured out how to use the for loop but I'm not entirely sure if there's a specific function I can use to only show every 3rd number. I feel like I might be on the right path when using car/cdr function except I'm getting an error
rest: contract violation
expected: (and/c list? (not/c empty?))
given: 0
My code:
(for/list ([x (in-range 20)] #:when (car(cdr(cdr x)))) (displayln x))
I'm trying to make a for loop that iterates over a list of numbers and prints out every 3rd number.
Typically it is more useful to create a new list with the desired values, and then print those values, or pass them to a function, or do whatever else may be needed. for/list does indeed return a list, and this is one reason for problems encountered by OP example code. (Other problems in OP code include that x is a number with [x (in-range 20)], so (cdr x) is not defined).
A possible solution would be to recurse over the input list, using take to grab the next three values, keeping the third, and using drop to reduce the input list:
;; Recurse using `take` and `drop`:
(define (every-3rd-1 lst)
(if (< (length lst) 3)
'()
(cons (third (take lst 3))
(every-3rd-1 (drop lst 3)))))
Another option would be to recurse on the input list using an auxiliary counter; starting from 1, only keep the values from the input list when the counter is a multiple of 3:
;; Recurse using an auxilliary counter:
(define (every-3rd-2 lst)
(define (every-3rd-helper lst counter)
(cond [(null? lst)
'()]
[(zero? (remainder counter 3))
(cons (first lst) (every-3rd-helper (rest lst) (add1 counter)))]
[else (every-3rd-helper (rest lst) (add1 counter))]))
(every-3rd-helper lst 1))
Yet another possibility would be to use for/list to build a list; here i is bound to values from the input list, and counter is bound to values from a list of counting numbers:
;; Use `for/list` to build a list:
(define (every-3rd-3 lst)
(for/list ([i lst]
[counter (range 1 (add1 (length lst)))]
#:when (zero? (remainder counter 3)))
i))
This function (or any of them, for that matter) could be usefully generalized to keep every nth element:
;; Generalize to `every-nth`:
(define (every-nth n lst)
(for/list ([i lst]
[counter (range 1 (add1 (length lst)))]
#:when (zero? (remainder counter n)))
i))
Finally, map could be used to create a list containing every nth element by mapping over a range of every nth index into the list:
;; Use `map` and `range`:
(define (every-nth-map n lst)
(map (lambda (x) (list-ref lst x)) (range (sub1 n) (length lst) n)))
If what OP really requires is simply to print every third value, rather than to create a list of every third value, perhaps the code above can provide useful materials allowing OP to come to a satisfactory conclusion. But, each of these functions can be used to print results as OP desires, as well:
scratch.rkt> (for ([x (every-3rd-1 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-3rd-2 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-3rd-3 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-nth 3 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-nth-map 3 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
Here is a template:
(for ([x (in-list xs)]
[i (in-naturals]
#:when some-condition-involving-i)
(displayln x))
I want to count the elements in a list and return a list containing the elements paired with them respective quantity
Something like that:
Input:
(count-elements '(a b d d a b c c b d d))
Output:
((a 2) (b 3) (d 4) (c 2))
How can I do it? I'm not having any success trying to pair the element and its accounting
Your problem can be divided into three broad parts:
Duplicate recognition/ deletion : This can be done by either removing all the duplicates of every element, or by knowing that the current element is a duplicate(and thus not counting it as a new element.). This(the former strategy) can be done by using the function remove-duplicates
Counting: A way to actually count the elements. This can be done by the function count
Combination: A way to combine the results into a list. This can be done by the macro push.
The Code:
(defun count-elements (lst)
(loop for i in (remove-duplicates lst)
with ans = nil
do (push (list i (count i lst)) ans)
finally (return ans)))
CL-USER> (count-elements '(a a b c))
((C 1) (B 1) (A 2))
CL-USER> (count-elements '(a b c d d a b s a c d))
((D 3) (C 2) (A 3) (S 1) (B 2))
CL-USER>
NOTE: The result might not be arranged as you would expect, because of the value returned by remove-duplicates
EDIT: As pointed out by coredump, a better version of count-elements would be:
(defun count-elements (lst)
(map 'list
(lambda (e)
(list e (count e lst)))
(remove-duplicates lst)))
which, instead of using loop, uses map.
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 '())).
I have a list that looks like (A (B (C D)) (E (F))) which represents this tree:
A
/ \
B E
/ \ /
C D F
How do I print it as (A B E C D F) ?
This is as far as I managed:
((lambda(tree) (loop for ele in tree do (print ele))) my-list)
But it prints:
A
(B (C D))
(E (F))
NIL
I'm pretty new to Common LISP so there may be functions that I should've used. If that's the case then enlight me.
Thanks.
Taking your question at face value, you want to print out the nodes in 'breadth-first' order, rather than using one of the standard, depth-first orderings: 'in-order' or 'pre-order' or 'post-order'.
in-order: C B D A E F
pre-order: A B C D E F
post-order: C D B F E A
requested order: A B E C D F
In your tree structure, each element can be either an atom, or a list with one element, or a list with two elements. The first element of a list is always an atom.
What I think the pseudo-code needs to look like is approximately:
Given a list 'remains-of-tree':
Create empty 'next-level' list
Foreach item in `remains-of-tree`
Print the CAR of `remains-of-tree`
If the CDR of `remains-of-tree` is not empty
CONS the first item onto 'next-level'
If there is a second item, CONS that onto `next-level`
Recurse, passing `next-level` as argument.
I'm 100% sure that can be cleaned up (that looks like trivial tail recursion, all else apart). However, I think it works.
Start: (A (B (C D)) (E (F)))
Level 1:
Print CAR: A
Add (B (C D)) to next-level: ((B (C D)))
Add (E (F)) to next-level: ((B (C D)) (E (F)))
Pass ((B (C D) (E (F))) to level 2:
Level 2:
Item 1 is (B (C D))
Print CAR: B
Push C to next-level: (C)
Push D to next-level: (C D)
Item 2 is (E (F))
Print CAR: E
Push F to next-level: (C D F)
Pass (C D F) to level 3:
Level 3:
Item 1 is C
Print CAR: C
Item 2 is D
Print CAR: D
Item 3 is F
Print CAR: F
It seems that the way you represent your list is inconsistent. For your example, I imagine it should be: (A ((B (C D)) (E (F)))). This way, a node is consistently either a leaf or a list where the car is the leaf and the cadr is the children nodes.
Because of this mistake, I am assuming this is not a homework. Here is a recursive solution.
(defun by-levels (ts)
(if (null ts)
'()
(append
(mapcar #'(lambda (x) (if (listp x) (car x) x)) ts)
(by-levels (mapcan #'(lambda (x) (if (listp x) (cadr x) '())) ts)))))
by-levels takes a list of nodes and collects values of the top-level nodes, and recursively find the next children to use as the next nodes.
Now,
(defun leafs-of-tree-by-levels (tree)
(by-levels (list tree)))
(leafs-of-tree-by-levels '(a ((b (c d)) (e (f)))))
; (A B E C D F)
I hope that makes sense.
My Lisp is a little rusty, but as Jonathan suggested, a breadth-first tree walk should do it - something along these lines
Edit: I guess I read the problem a little too quickly before. What You have is basically a syntax tree of function applications, so here is the revised code. I assume from your description of the problem that if C and D are children of B then you meant to write (B (C)(D))
; q is a queue of function calls to print
(setq q (list the-original-expression))
; for each function call
(while q
; dequeue the first one
(setq a (car q) q (cdr q))
; print the name of the function
(print (car a))
; append its arguments to the queue to be printed
(setq q (append q)(cdr a))
)
This is the history:
q: ( (A (B (C)(D))(E (F))) )
print: A
q: ( (B (C)(D))(E (F)) )
print: B
q: ( (E (F))(C)(D) )
print: E
q: ( (C)(D)(F) )
print: C
q: ( (D)(F) )
print: D
q: ( (F) )
print: F
q: nil