I working on a lisp function that will accept two parameters, the second of which is a list. It will take the first parameter and add it after every element of the second parameter. This is as far as I got:
(defun rd(list n1 lis2)
(rd ((n1) (cdr (lis2))))
(cons (n1) (cons (car (lis2))))
)
If the two parameters are 'aa and '(b c d f), the desired output should be: aa b aa c aa d aa f aa
Don't put variables inside (), that's for calling functions.
If the function takes two parameters, the parameter list should just be (n1 lis2), no need for list before that.
You're not doing anything with the result of the recursive call. You need to combine it with n1 and the first element of lis2.
A recursive function has to check for the base case, otherwise it will recurse infinitely.
(defun rd (n1 lis2)
(if (null lis2)
(list n1) ;; Add n1 at the end
(list* n1 (car lis2) (rd n1 (cdr lis2))))) ;; put n1 before every element
(rd 'aa '(1 2 3 4 5)) ;; => (aa 1 aa 2 aa 3 aa 4 aa 5 aa)
If you want insert the element after each head of the input list:
(defun f (a l)
(cond
((null l) l)
(T (cons (car l) (cons a (f a (cdr l)))))
)
)
(format t "~a" (f 'aa '(1 2 3 3 4 5 5 6)))
(1 AA 2 AA 3 AA 3 AA 4 AA 5 AA 5 AA 6 AA)
In this case, if l is an empty list, the output will be NIL.
Otherwise if you want insert the element before every tail of the list (included the last tail, i.e. the empty list)
(defun f (a l)
(cond
((null l) (list a))
(T (cons a (cons (car l) (f a (cdr l)))))
)
)
In this case:
(format t "~a" (f 'aa '(1 2 3 3 4 5 5 6)))
(AA 1 AA 2 AA 3 AA 3 AA 4 AA 5 AA 5 AA 6 AA)
If l is an empty list, the output will be the list (aa).
Related
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'm quite new to LISP and I am trying to work on the cond statement for class. Currently, I am attempting to check if the value passed is a list and if so, append the letter d onto the list.
Here is my code:
(defun test(L)
(listp L)
(cond ((listp L) (append L (list 'd)))
)
(write L)
)
(test (list 'a 'b 'c))
The output I get is:
(A B C)
(A B C)
If I change the test to: (test (car(list 'a 'b 'c)))
The new output I get is:
A
A
Two things I am wondering is
1.) Why isn't D appended onto the list if the first test passes a list?
2.) Why are they being printed twice? I'm using LISP Works so I figure it's actually something with how it always outputs the final value or something.
1.) The same reason str + "d" doesn't mutate str in Java or Python. It creates a new list that you do not use!
>>> str + "d"
'abcd'
>>> str
'abc'
Crazy similar isn't it?
2.) In CL the return is the last evaluated expression. The REPL prints every top level expression result to the terminal. Python does this too:
>>> def test():
... x = 2 + 3
... print x
... return x
...
>>> test()
5
5
Update
How to mutate the argument list. The simple answer is that you need to mutate the last pair of the argument instead:
(defun test (l)
(assert (consp 1) (l) "l needs to be a non nil list. Got: ~a" l)
(nconc l (list 'd)
(write l)))
(defparameter *test1* (list 1 2 3))
(defparameter *test1-copy* *test1*)
(test *test1*) ; ==> (1 2 3 d) (and prints (1 2 3 d))
*test1* ; ==> (1 2 3 d)
*test1-copy* ; ==> (1 2 3 d)
(eq *test1* *test1-copy*) ; ==> t
(test '())
** error l needs to be a non nil list. Got: NIL
(nconc l x) does (setf (cdr (last l)) x)
If you need to alter the binding, then you need to make a macro:
(defmacro testm (var)
(assert (symbolp var) (var) "List needs to be a variable binding. Got: ~a" var)
`(progn
(when (listp ,var)
(setf ,var (append ,var (list 'd)))
(write ,var))))
(macroexpand '(testm *test2*))
; ==> (progn
; (when (consp *test2*)
; (setf *test2* (append *test2* (list 'd))))
; (write *test2*))
(defparameter *test2* (list 1 2 3))
(defparameter *test2-copy* *test2*)
(testm *test2*) ; ==> (1 2 3 d) (and prints (1 2 3 d))
*test2* ; ==> (1 2 3 d)
*test2-copy* ; ==> (1 2 3)
(eq *test2* *test2-copy*) ; ==> nil
(defparameter *x* nil)
(testm *x*) ; ==> (d) (and prints (d))
*x* ; ==> (d)
(testm '(1))
** error List needs to be a variable binding. Got: '(1)
Idiomatic way to do it
(defun test (list)
(if (consp list)
(append list '(d))
list))
(write (test '(1 2 3)))
; ==> (1 2 3 d) (and prints (1 2 3 d))
(defparameter *test3* '(1 2 3))
(setf *test3* (test *test3*))
*test3* ; ==> (1 2 3 d)
Why following function (match-redefine) is not working?
(define vlist (list 10 20 30))
(match-define (list aa bb cc) (list 1 2 3))
(define alist (list aa bb cc))
alist
vlist
(define (match-redefine dst_list src_list)
(for ((d dst_list)(s src_list)) (set! d s)) )
(rnmatch-redefine alist vlist)
alist
vlist
The output is:
'(1 2 3)
'(10 20 30)
'(1 2 3)
'(10 20 30)
The destination list (alist) remains unchanged. Can this function be made to work?
Edit: I tried vector as suggested by #OscarLopez in the answers, but it does not work:
(match-define (list a b c) (list 0 0 0 ) )
(define variable_vect (vector a b c))
a
b
c
(define valuelist (list 1 2 3) )
(for ((i variable_vect)(j valuelist)) ; does not work
(set! i j))
variable_vect
a
b
c
(set! variable_vect valuelist)
(println "------- after ----------")
variable_vect
a
b
c
Output is:
0
0
0
'#(0 0 0)
0
0
0
"------- after ----------"
'(1 2 3)
0
0
0
Edit: It seems I will have to use special class to apply this:
(define myob%
(class object%
(super-new)
(init-field val)
(define/public (getval) val)
(define/public (setval v) (set! val v)) ))
(define (copyvalues objlist valuelist)
(for ((a alist)(v valuelist)) (send a setval v)) )
(define (show_objlist alist)
(for ((a alist)) (println (send a getval))) )
; USED AS FOLLOWS:
(define ob1 (make-object myob% 5))
(define ob2 (make-object myob% 5))
(define ob3 (make-object myob% 5))
(define alist (list ob1 ob2 ob3))
(println "---------- first assignment -----------")
(define vlist (list 1 2 3))
(copyvalues alist vlist)
(show_objlist alist)
(println "---------- second assignment -----------")
(define ylist (list 10 20 30))
(copyvalues alist ylist)
(show_objlist alist)
(println "---------- individual access -----------")
(send ob1 getval)
(send ob3 getval)
Output is:
"---------- first assignment -----------"
1
2
3
"---------- second assignment -----------"
10
20
30
"---------- individual access -----------"
10
30
You ask why the function is not working.
The reason is that (set! d s) is doing something
you do not expect.
Observe:
#lang racket
(define vlist (list 10 20 30))
(match-define (list aa bb cc) (list 1 2 3))
(define alist (list aa bb cc))
alist
vlist
(define (match-redefine dst_list src_list)
(for ((d dst_list)(s src_list))
(set! d s)
(displayln (~a "d is now: " s))))
(match-redefine alist vlist)
The output is:
'(1 2 3)
'(10 20 30)
d is now: 10
d is now: 20
d is now: 30
This means that you change the value of d (not the value of the variable which corresponds to the symbols that d runs through.
See your previous question on the same topic.
Again, this is not the way we do things in Scheme. Besides, your code is simply reassigning a local variable that was pointing to an element in the list, the destination list remains unmodified.
You could use vectors instead of lists - those can be modified, exactly as you would modify an array in the most common programming languages, something like this:
(define value_list (list 1 2 3))
(define value_vect (vector 0 0 0))
value_vect
=> '#(0 0 0)
(for [(i (in-range (vector-length value_vect)))
(value value_list)]
(vector-set! value_vect i value))
value_vect
=> '#(1 2 3)
Anyway you should not modify a list of variables, just return a list with the new values. And don't think about mutating the list - although it is possible to do so using mutable pairs, that's not the correct way to deal with this situation, please stop thinking about mutating everything you encounter!
I am new to lisp programming and i am trying to think about the below operation.
(extract '(0 1 0) '(a b c)) give us '(a b a)
(extract '(1 1 1 ) '(a b c)) gives us '(b b b)
how can i think about this and how to solve it.
As Chris Jester-Young described, it just returns elements from second list at indexes in first list. Writing such a function is very easy:
(defun extract (list-1 list-2)
(mapcar (lambda (n) (nth n list-2)) list-1))
CL-USER>(extract '(0 1 0) '(a b c))
(A B A)
CL-USER>(extract '(1 1 1 ) '(a b c))
(B B B)
If there no such index, it'll give you NIL in that place.
CL-USER> (extract '(1 100 1 ) '(a b c))
(B NIL B)
But this won't work on nested structures (trees). If you want it to return elements of list-2 shaped in the structure of list-1, you can use a simple maptree helper function, then do the same thing:
(defun maptree (fn tree)
(cond
((null tree) tree)
((atom tree) (funcall fn tree))
(t (cons
(maptree fn (first tree))
(maptree fn (rest tree))))))
(defun extract* (list-1 list-2)
(maptree (lambda (n)
(nth n list-2)) list-1))
CL-USER> (extract* '(3 (2 1 (0))) '(a b c d))
(D (C B (A)))
(extract a b) returns a copy of a where each element is replaced by the element of b in that position.
I have two lists: (1 2 3) and (a b) and I need to create something like this (1 2 3 1 2 3). The result is a concatenation of the first list as many times as there are elements in the second. I should use some of the functions (maplist/mapcar/mapcon, etc.). This is exactly what I need, although I need to pass first list as argument:
(mapcan #'(lambda (x) (list 1 2 3)) (list 'a 'b))
;=> (1 2 3 1 2 3)
When I try to abstract it into a function, though, Allegro freezes:
(defun foo (a b)
(mapcan #'(lambda (x) a) b))
(foo (list 1 2 3) (list 'a 'b))
; <freeze>
Why doesn't this definition work?
There's already an accepted answer, but I think some more explanation about what's going wrong in the original code is in order. mapcan applies a function to each element of a list to generate a bunch of lists which are destructively concatenated together. If you destructively concatenate a list with itself, you get a circular list. E.g.,
(let ((x (list 1 2 3)))
(nconc x x))
;=> (1 2 3 1 2 3 1 2 3 ...)
Now, if you have more concatenations than one, you can't finish, because to concatenate something to the end of a list requires walking to the end of the list. So
(let ((x (list 1 2 3)))
(nconc (nconc x x) x))
; ----------- (a)
; --------------------- (b)
(a) terminates, and returns the list (1 2 3 1 2 3 1 2 3 ...), but (b) can't terminate since we can't get to the end of (1 2 3 1 2 3 ...) in order to add things to the end.
Now that leaves the question of why
(defun foo (a b)
(mapcan #'(lambda (x) a) b))
(foo (list 1 2 3) '(a b))
leads to a freeze. Since there are only two elements in (a b), this amounts to:
(let ((x (list 1 2 3)))
(nconc x x))
That should terminate and return an infinite list (1 2 3 1 2 3 1 2 3 ...). In fact, it does. The problem is that printing that list in the REPL will hang. For instance, in SBCL:
CL-USER> (let ((x (list 1 2 3)))
(nconc x x))
; <I manually stopped this, because it hung.
CL-USER> (let ((x (list 1 2 3)))
(nconc x x) ; terminates
nil) ; return nil, which is easy to print
NIL
If you set *print-circle* to true, you can see the result from the first form, though:
CL-USER> (setf *print-circle* t)
T
CL-USER> (let ((x (list 1 2 3)))
(nconc x x))
#1=(1 2 3 . #1#) ; special notation for reading and
; writing circular structures
The simplest way (i.e., fewest number of changes) to adjust your code to remove the problematic behavior is to use copy-list in the lambda function:
(defun foo (a b)
(mapcan #'(lambda (x)
(copy-list a))
b))
This also has an advantage over a (reduce 'append (mapcar ...) :from-end t) solution in that it doesn't necessarily allocate an intermediate list of results.
You could
(defun f (lst1 lst2)
(reduce #'append (mapcar (lambda (e) lst1) lst2)))
then
? (f '(1 2 3) '(a b))
(1 2 3 1 2 3)
Rule of thumb is to make sure the function supplied to mapcan (and destructive friends) creates the list or else you'll make a loop. The same applies to arguments supplied to other destructive functions. Usually it's best if the function has made them which makes it only a linear update.
This will work:
(defun foo (a b)
(mapcan #'(lambda (x) (copy-list a)) b))
Here is some alternatives:
(defun foo (a b)
;; NB! apply sets restrictions on the length of b. Stack might blow
(apply #'append (mapcar #'(lambda (x) a) b))
(defun foo (a b)
;; uses loop macro
(loop for i in b
append a))
I really don't understand why b cannot be a number? You're really using it as church numbers so I think I would have done this instead:
(defun x (list multiplier)
;; uses loop
(loop for i from 1 to multiplier
append list))
(x '(a b c) 0) ; ==> nil
(x '(a b c) 1) ; ==> (a b c)
(x '(a b c) 2) ; ==> (a b c a b c)
;; you can still do the same:
(x '(1 2 3) (length '(a b))) ; ==> (1 2 3 1 2 3)