coerce function in common lisp -- arrays and lists - lisp

I am seeing different behavior of coerce between different versions of Common Lisp - wondering which one is "right" or is the standard ambiguous on this seemingly simple question:
is
(coerce '(1 2 3) 'array)
correct lisp? It works fine in Clozure Common Lisp but not in sbcl.
And when it does not work what is the easiest way to coerce a list into an array?
Thanks

The specification says:
If the result-type is a recognizable subtype of vector, and the object is a sequence, then the result is a vector that has the same elements as object.
array is not a subtype of vector -- vectors are 1-dimensional arrays, but array includes arrays with any number of dimensions.
You can use one of these
(coerce '(1 2 3) 'vector)
(coerce '(1 2 3) '(array t (*)))
In the second version, (*) specifies a single dimension whose size is unspecified.
Your use is unspecified, so implementations are free to implement it as they please. If it returns a value, the value has to be an ARRAY of some kind.

To add to Barmar's answer (this is really a comment, but it's too long), while it's fine for CCL to do what it does, I think it's clear that something like this would be very hard to define in a standard.
Consider something like this:
(coerce '((1 2 3) (4 5 6) (7 8 9)) 'array)
What is the result of this meant to be? Should it be:
a vector each of whose elements is a three-element list?
the equivalent of (make-array '(3 3) :initial-contents '((1 2 3) (4 5 6) (7 8 9)))?
the transpose of that array?
I think either of the first two are reasonable interpretations: sometimes you will want one, sometimes the other. The third is probably not reasonable given CL is a row-major language.
So if (coerce ... 'array) were in the standard, how would you specify which of these you wanted? If you just chose one, which should it be (and how do you now reach agreement with the people on the committee who think it should be the other!)?

Related

how to find element of list by knowing its position in clisp?

If I know the position of an element in a list in clisp, then how could I retrieve the element knowing its position. Is there any predefined function for it?
For lists only there is NTH:
CL-USER> (nth 2 '(1 2 3 4 5))
3
For SEQUENCES (vectors, strings, lists ...) there is ELT:
CL-USER> (elt '(1 2 3 4 5) 2)
3
If you really need a lot to access element by index, I'll advice you to consider using vectors (and access elements by aref) instead of lists, especially if you have logn sequences, because accessing element by index in lists may need to travel along all list to your element.
Of course, if you have small amount of data, you wan't feel any difference, but it looks good to use things right for me.
I depends on your lisp flavour. The best thing is to just write a 2 parameter function which returns a list-item. Parameter 1 item_index, param 2 the list, just recursively reduce index as you move through and return the 0th of 1st index. Note you need to decide if the car of a list is index 1 or index 0. Humans prefer one,computers 0.

What is the algorithm used by programming languages to eval ASTs? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
What is the algorithm used by programming languages to eval their ASTs?
That is, suppose we have 4 basic functions, /*+-. What is a basic algorithm that will correctly eval any AST in the form of, for example:
(+ (- (* 3 2) (+ (/ 5 2))) (* 2 4))
My doubt is actually what happens if the evaluation of a node returns something that still have to be evaluated. For example, in Scheme, the evaluation of ((lambda (a) (+ a 2)) 3) would be (+ 3 2). But this could be evaluated again into 5. So how does the language determine when to stop evaluating a form?
You're totally misunderstanding how Scheme/Lisp evaluation works. I'll use the example you gave:
(+ (- (* 3 2) (+ (/ 5 2))) (* 2 4))
To evaluate a list, we evaluate each of the elements. The first is expected to return a procedure (I'm ignoring the special case of syntax operators), the rest can return arbitrary values. We call the procedure with the rest as arguments.
At the top level, this is a list of 3 elements:
+
(- (* 3 2) (+ (/ 5 2)))
(* 2 4)
Each of these is evaluated. The first is a variable whose value is a procedure (Scheme's built-in addition function). The others, being lists, require recursion into the evaluation algorithm. I'm going to skip describing the second one, because of its complexity, and go to the third: (* 2 4).
This is a list of 3 elements: *, 2, and 4. As above, * is the multiplication function. 2 and 4 are literals, so they evaluate to themselves. So we call the multiplication function with the arguments 2 and 4, and it returns 8.
The complicated second argument goes through the same process, just with several more levels of recursion. It eventually returns 4. So we then call the multiplication function with the arguments 4 and 8, and it returns 32.
Your second example is processed similarly. At the top, you have a list of two elements:
(lambda (a) (+ a 2))
3
Each of these is evaluated. Lambda is special syntax that parses its contents and returns a procedure that evaluates its body in a context where the parameter variables are bound to arguments, so the first returns a procedure that adds 2 to its argument and returns that. 3 is a literal, so it just returns the number 3. We then call the procedure with the argument 3, it adds 2 to it and returns 5.
In the case you give, the execution will stop at 5, since it is a literal value and represents itself. This is not hard to test for. You might as well ask how a function that traverses a list in depth knows how to stop (in fact, you should, since in Scheme this is the same thing).
In Scheme, any compound expression should eventually resolve to one of the 7 primitive datatypes or the empty list, unless it becomes trapped in an infinite loop. If you want to know in advance if the expression will resolve, well, that's an interesting problem: http://en.wikipedia.org/wiki/Halting_problem
I think you may be asking the wrong question, but I will try:
Until it gets a result that it can work with. In your example you're asking about when an interpeter stops evaluating an expression... its 100% language depedent and would be a completely different answer if you were to ask about a compiler. For your Scheme example, you would need to read the Scheme specification (R5RS).
So it is defined by the writer of the interpreter. If a single literal (or even variable) is the expected result of an expression in my language, then it would stop there.
There are many different algorithms.
Alternative 1: You could compile the AST to an intermediate representation which is more linear. Your code could be compiled to something like the following:
a <- 3 * 2
b <- 5 / 2
c <- a - b
d <- 2 * 4
e <- c + d
return e
This is easy to evaluate, since it is just a sequence of instructions. Most of the instructions have the same format: X <- Y OP Z, so the evaluator will be very simple.
Alternative 2: You can compile alternative #1 to machine code or byte code.
li r3, 3
muli r3, 2
li r4, 5
divi r4, r5, 2
subf r3, r3, r4
li r4, 2
muli r4, r4, 4
add r3, r3, r4
blr
Alternative 3: You can compile alternative #1 to a special form called SSA, or "single static assignment", which is similar to #1 but the LHS of every assignment is unique, and special "phi" nodes are used to combine values from different branches. SSA can then be compiled to machine code or byte code.
Alternative 4: You can evaluate the AST by recursive descent. This is covered thoroughly in most books on Scheme / Lisp.
Alternative 5: You can use recursive descent to convert the code to stack machine code, and then evaluate that. Something like:
push 3
push 2
mul
push 5
push 2
div
sub
push 2
push 4
mul
add
ret
Alternative ∞: There are plenty of other techniques. The books written on this subject are thick.

Negative infinity in Lisp

I'm looking for the standard way to represent negative infinity in Lisp. Is there a symblic value which is recognised by Lisp's arithmetic functions as less than all other numbers?
Specifically, I'm looking for an elegant way to write the following:
(defun largest (lst)
"Evaluates to the largest number in lst"
(if (null lst)
***negative-inifinity***
(max (car lst) (largest (cdr lst)))))
ANSI Common Lisp has bignum, which can used to represent arbitrarily large numbers as long as you have enough space, but it doesn't specify an "infinity" value. Some implementations may, but that's not part of the standard.
In your case, I think you've got to rethink your approach based on the purpose of your function: finding the largest number in a list. Trying to find the largest number in an empty list is invalid/nonsense, though, so you want to provide for that case. So you can define a precondition, and if it's not met, return nil or raise an error. Which in fact is what the built-in function max does.
(apply #'max '(1 2 3 4)) => 4
(apply #'max nil) => error
EDIT: As pointed by Rainer Joswig, Common Lisp doesn't allow arbitrarily long argument lists, thus it is best to use reduce instead of apply.
(reduce #'max '(1 2 3 4))
There is nothing like that in ANSI Common Lisp. Common Lisp implementations (and even math applications) differ in their representation of negative infinity.
For example in LispWorks for double floats:
CL-USER 23 > (* MOST-NEGATIVE-DOUBLE-FLOAT 10)
-1D++0

Lisp - List of lists with variable size

I have to represent a board game using lisp. To do that i have to create a function that builds the board.
This function receives an integer that represents the number of sublist the original list as to have. each one of this sublists have a different size growing in 3*n proportion.
As an example ifthe function is called with the number 3, it will create a list with 3 sublists, the first with 3 position, the second with six and the third with 9.
Also, each of the positions need to be initialized with ´*.
To do this i think i have to make a recursive call to make-list, but i can't seem to do that right. i'be tried to use the 'dotimes' cycle to do that, but i didn't have any sucess with that.
So far i have:
(defun faz-tabuleiro (n_aneis)
(make-list n_aneis :initial-element (...)
Wich creates the main list, but how can i represent the sublists inside with the right size?
Does this do what you want?
(defun make-table (n)
(loop :for i :from 1 :to n
:collect (make-list (* i 3) :initial-element "*")))
Map over a list of numbers being the length of the sublists. Use a function for this mapping which returns the right list initialized with the initial element.

extract/slice/reorder lists in (emacs) lisp?

In python, you might do something like
i = (0, 3, 2)
x = [x+1 for x in range(0,5)]
operator.itemgetter(*i)(x)
to get (1, 4, 3).
In (emacs) lisp, I wrote this function called extract which does something similar,
(defun extract (elems seq)
(mapcar (lambda (x) (nth x seq)) elems))
(extract '(0 3 2) (number-sequence 1 5))
but I feel like there should be something built in? All I know is first, last, rest, nth, car, cdr... What's the way to go? ~ Thanks in advance ~
If your problem is the speed then use (vector 1 2 3 4 5) instead of a list, and (aref vec index) to get the element.
(defun extract (elems seq)
(let ((av (vconcat seq)))
(mapcar (lambda (x) (aref av x)) elems)))
If you're going to extract from the same sequence many times of course it make sense to store the sequence in a vector just once.
Python lists are indeed one-dimensional arrays, the equivalent in LISP are vectors.
I've only done simple scripting in elisp, but it's a relatively small language. And extract is a very inefficient function on linked lists, which is the default data structure in emacs lisp. So it's unlikely to be built-in.
Your solution is the best straightforward one. It's n^2, but to make it faster requires a lot more code.
Below is a guess at how it might work, but it might also be totally off base:
sort elems (n log n)
create a map that maps elements in sorted elem to their indices in original elem (probably n log n, maybe n)
iterate through seq and sorted elem. Keep only the indices in sorted elem (probably n, maybe n log n, depending on whether it's a hash map or a tree map)
sort the result by the values of the elem mapping (n log n)
From My Lisp Experiences and the Development of GNU Emacs:
There were people in those days, in 1985, who had one-megabyte machines without virtual memory. They wanted to be able to use GNU Emacs. This meant I had to keep the program as small as possible.
For instance, at the time the only looping construct was ‘while’, which was extremely simple. There was no way to break out of the ‘while’ statement, you just had to do a catch and a throw, or test a variable that ran the loop. That shows how far I was pushing to keep things small. We didn't have ‘caar’ and ‘cadr’ and so on; “squeeze out everything possible” was the spirit of GNU Emacs, the spirit of Emacs Lisp, from the beginning.
Obviously, machines are bigger now, and we don't do it that way anymore. We put in ‘caar’ and ‘cadr’ and so on, and we might put in another looping construct one of these days.
So my guess is, if you don't see it, it's not there.