I have two vector array :
t1 (vector 1 2 3)
t2 (vector 1 2 3 6 4)
I just want sum the value of t1 with t2
The result is like this :
t2 (2 4 6 6 4)
First i try this code :
(defun addition-v2 (t1 t2)
(if(< (length t1) (length t2))
(do ((x 0 (+ 1 x)))
((>= x (length t1)) t2)
(setf (aref t2 x) (+ (aref t1 x) (aref t2 x))))))
Like you imagine the result is
#(2 4 6 6 4)
Ok fine, but how can i do if length of t1 > length of t2
Since you destructively update t2, you can use MAP-INTO.
(defun addition-v2 (t1 t2)
(when (> (length t1) (length t2))
(rotatef t1 t2))
(map-into t2 #'+ t1 t2))
If you want to use the bottom-up & functional approach to this, here's how it would look:
(defun ensure-length (vec len)
(let ((vec-len (length vec)))
(if (< vec-len len)
(let ((result (make-array len
:initial-element 0)))
(dotimes (i vec-len)
(setf (elt result i)
(aref vec i)))
result)
vec)))
(defun ensure-lengths (vec1 vec2)
(values (ensure-length vec1 (length vec2))
(ensure-length vec2 (length vec1))))
(defun ensured-vector-add (vec1 vec2)
(multiple-value-bind (v1 v2)
(ensure-lengths vec1 vec2)
(map 'vector #'+ v1 v2)))
(defun ensured-vector-+ (&rest vs)
(reduce #'ensured-vector-add vs
:initial-value #()))
Then you can just call (ensured-vector-+ t1 t2) or however many vectors you have.
Finally found the problem with the size of t1 or t2, in this line :
((>= x (length c)) t2)
(>= x (length c) need to be < length c so I use function min.
Maybe there is other solution, but this one works !
(defun addition-v2 (t1 t2)
(if(< (length t1) (length t2))
(setq c t2)
(setq c t1))
(do ((x 0 (+ 1 x)))
((>= x (min (length t1) (length t2))) c)
(setf (aref t2 x) (+ (aref t1 x) (aref t2 x))))))
Related
I am trying to change the elements on a list based on a criteria. Let's say I have a list,
L = '(0 1 1 0 0). I want only the first "zero" found in this list as "zero", and for any other "zero" in that list, I want them to be 1. So the list of my example will become L = '(0 1 1 1 1). This is what I have done so far,
(let dLoop ((L '(0 1 1 0 0))
(i 0)
(j 1))
(if (and (<= i (length L)) (<= j (- (length L) 1)))
(begin
(if (zero? (list-ref L i))
(begin
(cond
[(zero? (list-ref L j)) (list-set L j 1)]
[else (dLoop L i (add1 j))]
)
)
(dLoop L (add1 i) (add1 j))))
L))
This only returns, L = '(0 1 1 1 0)
For some reason, the moment it finds the first duplicate zero, the code terminates! I would really appreciate some insights regarding this issue
In your (cond) expression, you don't have a recursive call to dLoop if (zero? (list-ref L j)) case evaluates. This causes the (cond) to return, then the (begin) returns and finally exits out of you (let) expression. Adding on to what Lazer said however, this is kinda not the standard scheme approach, let alone very efficient since (list-ref) on linked-lists is O(n) each time. Perhaps try something like:
(define (find-and-map-rest lst pred f)
(cond [(null? lst) lst]
;; found the thing
[(pred (car lst)) (cons (car lst)
(map f (cdr lst)))]
;; didn't find the thing... yet
[else (cons (car lst)
(find-and-map-rest (cdr lst)
pred f))]))
(define (zero->one x)
(if (zero? x) 1 x))
(find-and-map-rest '(0 1 1 0 0) zero? zero->one)
Realistic code is probably not going to do all of that consing for a task like this. All that the code really needs to do is find the first zero, take the first part of the list up to and including that zero, and append it to a list of ones as long as the rest of the input list. If no zero is found, the result is just the input list:
(define (f xs)
(let ((rest (member 0 xs)))
(if rest
(let ((ones-count (sub1 (length rest))))
(append (take xs (- (length xs) ones-count))
(make-list ones-count 1)))
xs)))
Sample interaction:
scratch.rkt> (f '(0))
'(0)
scratch.rkt> (f '(1))
'(1)
scratch.rkt> (f '(0 1 1 0 0))
'(0 1 1 1 1)
scratch.rkt> (f '(1 1 0 1 1 1 0 0 1 0 1 0))
'(1 1 0 1 1 1 1 1 1 1 1 1)
I want to apply the function (* x 2) to every other element in a list and return the entire list using the loop macro. The solution I've come up with so far is this:
(defun double-every-other (xs)
(loop for x in xs by #'cddr collect (* x 2)))
However, this will double every other element and only return the elements that were doubled, so if I executed:
(double-every-other '(1 2 3 4))
The result would be:
'(4 8)
But I want the result to be:
'(1 4 3 8)
Is there a way I can do this using (loop)?
Another version with less math:
(defun double-every-other (list)
(loop
for (a b) on list by #'cddr
collect a
when b collect (* b 2)))
(double-every-other '(1 2 3 4))
=> (1 4 3 8)
(double-every-other '(1 2 3 4 5))
=> (1 4 3 8 5)
Obviously, you won't be able to abstract the N as easily as the other answer (if you are thinking "macro", stop now). Here we iterate using the on keyword, which means each sublist is visited in turn. Since we use by #'cddr, every other sublist is skipped. The destructuring syntax (a b) binds the first and second elements of the visited list.
You can for instance test an integer increasing while the list is scanned:
(defun double-every-other (xs)
(loop for x in xs
for i from 1
if (oddp i)
collect x
else collect (* x 2)))
(defun double-every-other (xs)
(loop for x in xs
for doublep = nil then (not doublep)
collect (if doublep (* x 2) x)))
another version, without loop at all:
(defun make-cycled (&rest items)
(setf (cdr (last items)) items))
(mapcar #'funcall
(make-cycled #'identity (lambda (x) (* 2 x)))
'(10 9 8 7 6 5 4 3))
;;=> (10 18 8 14 6 10 4 6)
You could use the loop "on" list iteration primitive. This takes a list of loop variables that will be "smeared" across the list, with the last being the tail of the entire remaining list. The conditional loop for is necessary to avoid multiplying nil if we have an odd number of arguments.
(defun double-every-other (list)
(loop for (single double tail) on list by #'cddr
if (null double)
collect single
else
append (list single (* 2 double))))
And if we try to run it:
* (double-every-other '(1 2 3 4 5))
(1 4 3 8 5)
Here is an iterative example of a procedure computing the fibonacci sequence in SICP. The idea is:
a = fib(n+1) = a+b
b = fib(n) = a
(define (fib n)
(fib-iter 1 0 n))
(define (fib-iter a b count)
(if (= count 0)
b
(fib-iter (+ a b) a (- count 1))))
Looking at it deeper, I don't understand why continuing the computation towards fib(n+1) is necessary. I found we could have written.
;; a and b are first and second integers respectively
;; in the recursive call, b would be replaced by a+b because it is the next number in the sequence
;; so now a will be replaced by the previous value of b because it is the previous value.
(define (fib2 n)
(fib-iter 1 0 n))
(define (fib-iter a b count)
(if (= count 0)
b
(fib-iter b (+ a b) (- count 1))))
Now, I really think the first example, the one continuing up to n+1 is really redundant. I don't understand why is that necessary. What's wrong with my proposed iterative example?
Bot procedures produce correct result. However, the first one retains the relationship between a and b: a is Fib(i+1) and b is Fib(i) where i=n-count. The second method uses the first iteration to swap a and b around, thus introducing one redundant iteration. This can be seen by taking the trace of procedures:
> (define (fib n)
(fib-iter 1 0 n))
(define (fib-iter a b count)
(if (= count 0)
b
(fib-iter (+ a b) a (- count 1))))
> (trace fib-iter)
> (fib 3)
>(fib-iter 1 0 3)
>(fib-iter 1 1 2)
>(fib-iter 2 1 1)
>(fib-iter 3 2 0)
<2
2
> (define (fib-iter a b count)
(if (= count 0)
b
(fib-iter b (+ a b) (- count 1))))
> (trace fib-iter)
> (fib 3)
>(fib-iter 1 0 3)
>(fib-iter 0 1 2)
>(fib-iter 1 1 1)
>(fib-iter 1 2 0)
<2
2
What you actually want is something like this:
> (define (fib n)
(if (zero? n)
0
(fib-iter 0 1 (- n 1))))
(define (fib-iter a b count)
(if (zero? count)
b
(fib-iter b (+ a b) (- count 1))))
> (trace fib-iter)
> (fib 3)
>(fib-iter 0 1 2)
>(fib-iter 1 1 1)
>(fib-iter 1 2 0)
<2
2
Notice, there is one less iteration. However, I'm doing extra work in procedure fib.
There is nothing wrong. The two approaches give the same result.
#lang racket
(define (fib n)
(fib-iter 1 0 n))
(define (fib-iter a b count)
(if (= count 0)
b
(fib-iter (+ a b) a (- count 1))))
(define (fib2 n)
(fib-iter2 1 0 n))
(define (fib-iter2 a b count)
(if (= count 0)
b
(fib-iter2 b (+ a b) (- count 1))))
(define xs '(0 1 2 3 4 5 6 7 8 9 10))
(map fib xs)
(map fib2 xs)
The output is:
'(0 1 1 2 3 5 8 13 21 34 55)
'(0 1 1 2 3 5 8 13 21 34 55)
This shows that you are indeed computing the same sequence.
How do we convert elegantly between arbitrarily nested lists and arrays?
e.g.
((1 2 3) (4 5 6))
becomes
#2A((1 2 3) (4 5 6))
and vice versa
List to 2d array:
(defun list-to-2d-array (list)
(make-array (list (length list)
(length (first list)))
:initial-contents list))
2d array to list:
(defun 2d-array-to-list (array)
(loop for i below (array-dimension array 0)
collect (loop for j below (array-dimension array 1)
collect (aref array i j))))
The multi-dimensional form for list to 2d is easy.
(defun list-dimensions (list depth)
(loop repeat depth
collect (length list)
do (setf list (car list))))
(defun list-to-array (list depth)
(make-array (list-dimensions list depth)
:initial-contents list))
The array to list is more complicated.
Maybe something like this:
(defun array-to-list (array)
(let* ((dimensions (array-dimensions array))
(depth (1- (length dimensions)))
(indices (make-list (1+ depth) :initial-element 0)))
(labels ((recurse (n)
(loop for j below (nth n dimensions)
do (setf (nth n indices) j)
collect (if (= n depth)
(apply #'aref array indices)
(recurse (1+ n))))))
(recurse 0))))
Another 2d array to list solution:
(defun 2d-array-to-list (array)
(map 'list #'identity array))
And list to 2d array (But maybe not as efficient as the solution of the last reply):
(defun list-to-2d-array (list)
(map 'array #'identity list))
Use coerce: Coerce the Object to an object of type Output-Type-Spec.
(coerce '(1 2 3) 'vector) => #(1 2 3)
(coerce #(1 2 3) 'list) => '(1 2 3)
Why does this code not print out the content of the array -
(defun loopfn (state)
(loop for x from 0 to 2 do
(loop for y from 0 to 2 do
(aref state x y))))
Here I am passing a 3x3 matrix which is built like this -
`(setq i (make-array '(3,3) :initial-contents '((0 1 3) (4 2 5) (7 8 6))))`
I am calling - (loopfn i)
Edit--------
#Greg
Thanks for pointing that out...
I had the following question..
Why does this print the output ...
(defun loopfn ()
(loop for x from 0 to 3 do
(if (eq x 2)(return (list x)))))
Where as this prints a nil...
(defun loopfn ()
(loop for x from 0 to 2 do
(loop for y from 0 to 2 do
(if (eq x 2)(return (list x y))))))
I am calling
(loopfn)
Your code does not print anything. That's also what you want - usually.
But you want functions to return something useful.
So you need to understand the difference between printing and having a REPL printing a return value.
CL-USER > 3
3
Above returns 3. The Read-Eval-Print-Loop prints the return value.
CL-USER > (print 3)
3
3
Above prints a newline and then two times the 3. Why?
The first is the side-effect of the PRINT call which prints the newline and then its argument.
The second is the REPL printing the return value.
Note also the EQ is not for numeric comparisons. Use EQL instead.
See: http://www.lispworks.com/documentation/lw50/CLHS/Body/f_eql.htm
As for your second question, (return ...) is equivalent to (return-from NIL ...) so you just return from your inner LOOP into the outer one. Use this instead:
[11]> (defun loopfn ()
(loop for x from 0 to 2 do
(loop for y from 0 to 2 do
(if (= x 2) (return-from loopfn (list x y))))))
[12]> (loopfn)
(2 0)
Another possibility is to collect more values than just one, as in
[36]> (defun loopfn ()
(loop for x from 0 to 2 nconc
(loop for y from 0 to 2
if (= y 2)
collect (list x y))) )
LOOPFN
[37]> (loopfn)
((0 2) (1 2) (2 2))
Your call to aref is getting the specified element, but you're not doing anything with it. You could stick it on to a list which is then returned:
(defun loopfn (state)
(let ((result '()))
(loop for x from 0 to 2 do
(loop for y from 0 to 2 do
(setf result (cons (aref state x y) result))))
result))
or you could just print it out:
(defun loopfn (state)
(loop for x from 0 to 2 do
(loop for y from 0 to 2 do
(format t "~a~%" (aref state x y)))))
The former is far more useful ; you want to return things which can then be further processed, and anything that gets passed to the top level will be printed out for you.
As long as you are using LOOP you can easily gather up your values with COLLECT, APPEND, etc., which is the idiomatic way to do it.
This was neatly covered in this forum topic.
The outer loop has no clause which would cause a return value.
Some code examples from that thread:
(defun print-2d-array-as-table (array)
(loop for i from 0 below (array-dimension array 0)
do (loop for j from 0 below (array-dimension array 1)
do (princ (aref array i j))
(if (= j (1- (array-dimension array 1)))
(terpri)
(princ #\Space)))))
and one loop:
(defun print-2d-array-as-table (array)
(loop for i below (array-total-size array) do
(if (zerop (mod i (array-dimension array 0)))
(terpri)
(princ #\Space))
(princ (row-major-aref array i))))
For your second question, in the loop that doesn't print, (eq x 2) is never true. You have modified the loop bounds from 0 to 3 to 0 to 2, so x never reaches 2. Since there is no explicit (return ...) executed, the function returns nil.