Common Lisp: convert between lists and arrays - arrays

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)

Related

How to convert a list to a one dimensional array (vector) in Common Lisp having the same output either using make-array or coerce?

I want to convert from a simple list:
'(1 2 3)
To a one dimensional array (vector):
#(1 2 3)
I found this question which is similar but does not cover this problem.
I also managed to find a way to achieve it. Not sure if it is the best:
CL-USER> (coerce '(1 2 3) 'vector)
#(1 2 3)
CL-USER> (type-of *)
(SIMPLE-VECTOR 3)
I wonder if it is possible to use make-array to achieve the same result. I tried:
CL-USER> (make-array '() :initial-contents '(1 2 3))
#0A(1 2 3)
CL-USER> (type-of *)
(SIMPLE-ARRAY T NIL)
This is close, but I do not understand #0A in #0A(1 2 3).
For some reason that I do not understand, this output does not work on further compositions, such as aref:
CL-USER> (aref #0A(1 2 3) 0)
; Evaluation aborted on #<SIMPLE-ERROR "Wrong number of subscripts, ~W, for array of rank ~W." {1003C07793}>.
Is it possible to use make-array to achieve the same result as coerce?
What are the differences between these two approaches?
Is one of them faster or more elegant than the other?
COERCE is fine, you can even specify the element-type if you want:
USER> (coerce '(1 2 3) '(vector fixnum))
#(1 2 3)
USER> (describe *)
#(1 2 3)
[simple specialized vector]
Element-type: FIXNUM
Length: 3
You can do the same with make-array, but you need to give the right dimension. The dimension parameter indicates how many rows, columns, etc. the possibly multi-dimensional array has. It should be a list, but when you only have one dimension, it can just be a number. Both forms here are equivalent:
USER> (make-array 3 :initial-contents '(1 2 3))
#(1 2 3)
USER> (make-array '(3) :initial-contents '(1 2 3))
#(1 2 3)
Usually you would call (length list). The added value compared to coerce is that you can specify the :fill-pointer or :adjustable arguments, something that the type argument of coerce cannot convey.
The printed representation of an array is #nA(), where n is the number of dimensions of the array, where the number and A is omitted if its a vector (n = 1). For example:
USER> (make-array '(10 2) :initial-element 0)
#2A((0 0) (0 0) (0 0) (0 0) (0 0) (0 0) (0 0) (0 0) (0 0) (0 0))
For a given array of dimension n, you access the elements with aref and as many arguments as there are dimensions, in row-major order (the same order you specified the dimensions in make-array).
USER> (aref * 5 1)
0 (0 bits, #x0, #o0, #b0)
In your example, you defined an array of dimension 0, because you wrote '() (a.k.a. just () or nil) as the dimension. This can be used if you need a box to store a single element:
USER> (defparameter *box* (make-array nil :element-type '(mod 8)))
*BOX*
USER> (describe *box*)
#0A0
[simple specialized array]
Element-type: (UNSIGNED-BYTE 4)
Dimensions: NIL
Storage vector: #<(SIMPLE-ARRAY (UNSIGNED-BYTE 4) (1)) {101EA0C59F}>
; No values
USER> (setf (aref *box*) 7)
7 (3 bits, #x7, #o7, #b111)
USER> (incf (aref *box*))
8 (4 bits, #x8, #o10, #b1000)
USER> (aref *box*)
8 (4 bits, #x8, #o10, #b1000)
(as you can see, the values that can be stored in the array are the ones corresponding to the upgraded-element-type, here (unsigned-byte 4); for example, (setf (aref *box*) (expt 2 16)) signals an error)
It looks like :initial-contents had the same result as :initial-element, because with your example the content of the zero-dimensional array was the list (1 2 3)
Is one of them faster or more elegant than the other?
I try to use coerce when possible because it's shorter to write and it looks more descriptive of what I am doing. I don't think it is faster, unless you know in advance the length of the list.

Common Lisp - apply function to every other element in list

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)

Clojure multiply first n elements in sequence by 'x' non recursive

I am a newbie in clojure and came across a problem which says, multiply first n elements in a sequence by some number 'x' (non recursively). So for example
(multiply-n-by-x [1 2 3 4 5] 2 10) => [10 20 30 4 5]
So here i understood that i need to loop over the sequence n times and then stop, but i am unable to do that. If someone could guide me on how to do about it, it would be great.
Same as Shawn's answer but with destructuring and split-at (a bit less redundant):
(defn multiply-n-by-x [s n x]
(let [[s1 s2] (split-at (inc n) s)]
(concat (map #(* x %) s1) s2)))
I think the easy way is :
(defn multiply-n-by-x [seq n m]
(concat (map #(* m %) (take (inc n) seq)) (drop (inc n) seq) )
)
This does what you want:
(defn multiply-n-by-x [sq n x]
(for [i (range (count sq)) ;for i in range 0 to number of elements in sq
:let [element (nth sq i)]] ;bind element to the nth item in sq
(if (<= i n) ;if index below n, return the multiplied element, otherwise return the element as is
(* x element)
element)))
whatever you return inside the for macro gets put into a sequence so the end result is collection.
Lazy sequences capture delayed recursion. take, drop, split and for are lazy constructions. We can avoid them by computing the altered head of the sequence eagerly, as follows:
(defn multiply-n-by-x [coll n x]
(loop [head [], coll coll, n n]
(if (and (seq coll) (>= n 0))
(recur (conj head (* (first coll) x)) (rest coll) (dec n))
(concat head coll))))
For example,
(multiply-n-by-x [1 2 3 4 5] 2 10)
;(10 20 30 4 5)
By the way, the convention in Clojure is to give the count of a slice, not the index of the final element, which is one less.
(range 3)
;(0 1 2)

Lisp array element swap

I'm new to lisp and I'm trying to trade two elements in an array. I would like to know if there is a function to get a specified position so I can use rotatef to swap them.
I've tried the function position but it doesn't work on arrays since it isn't a sequence.
What is the best computational solution in case there isn't a built in function for array?
I've searched around and can't seem to find a simple solution. Is row-major-aref the solution?
Basically, i want to find the position of an element in the 2 dimensional array and return the position to be used in rotatef
You can make a one-dimensional displaced array and use that as a vector for position.
Example:
CL-USER 9 > (let ((a0 (make-array '(2 3)
:initial-contents '((foo1 bar foo2)
(foo3 baz foo4)))))
(let ((a1 (make-array (reduce #'+ (array-dimensions a0))
:displaced-to a0)))
(let ((pos1 (position 'baz a1))
(pos2 (position 'bar a1)))
(when (and pos1 pos2)
(rotatef (aref a1 pos1)
(aref a1 pos2)))))
a0)
#2A((FOO1 BAZ FOO2) (FOO3 BAR FOO4))
I think it should work - arrays are indeed sequences.
(let* ((an-array (make-array 6 :initial-contents '(#\f #\o #\o #\b #\a #\r)))
(f-pos (position #\f an-array))
(r-pos (position #\r an-array)))
(rotatef (elt an-array f-pos)
(elt an-array r-pos))
an-array)
;=> #(#\r #\o #\o #\b #\a #\f)
Of course, you don't need to bind the positions to names. This will work too:
(let ((an-array (make-array 6 :initial-contents '(#\f #\o #\o #\b #\a #\r))))
(rotatef (elt an-array (position #\f an-array))
(elt an-array (position #\r an-array)))
an-array)
;=> #(#\r #\o #\o #\b #\a #\f)
If the problem is with position not finding the element you need, its :test argument may be helpful. There are also position-if and position-if-not functions which let you supply your own predicate for identifying the element. All three are described here in the HyperSpec.
Here's an example that probably won't work without the :test argument, since the default (which is eql for all sequence functions with :test arguments - see table 11-2 here for a nice summary of the standard sequence function keyword arguments) doesn't work on lists.
(let ((an-array (make-array 3 :initial-contents '((1 2 3)
(4 5 6)
(7 8 9)))))
(rotatef (elt an-array (position '(1 2 3) an-array :test #'equal))
(elt an-array (position '(7 8 9) an-array :test #'equal)))
an-array)
;=> ((7 8 9) (4 5 6) (1 2 3))
(Tested on SBCL 1.0.55.0.debian).
Added:
Here's a brute force way to do it with a two-dimensional array. find-position assumes the array is of size (3 3) but it would be easy to make it somewhat more general.
I don't advocate this as the best solution, but I didn't want to leave you empty handed after misunderstanding your question :)
(defvar an-array #2A((1 2 3) (4 5 6) (7 8 9)))
(defun find-position (array item &key (test #'eql))
(loop for i below 3 do
(loop for j below 3 do
(when (funcall test (aref array i j) item)
(return-from find-position (list i j))))))
(defun swap-4-and-7 (array)
;; Example use
(destructuring-bind (i1 j1) (find-position array 4)
(destructuring-bind (i2 j2) (find-position array 7)
(rotatef (aref array i1 j1)
(aref array i2 j2))))
array)
(swap-4-and-7 an-array)
;=> #2A((1 2 3) (7 5 6) (4 8 9))

Printing contents of array LISP

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.

Resources