Lisp, calculating mixed expressions - lisp

i'am currently trying lisp and i need to solve a Problem. I want to write a function that takes a list as input and returns the calculated number. The elements that are not numbers should be added at the end of the list. Its important that the caluclated number is in front. At the end of this post you can see some function calls with the output i'am looking for.
(Function '(+ 100 1 2 3 4 5 6));-> 121
(Function '(+ 1 2 A B 3 C));-> (+ 6 C B A)
(Function '(+ A B C D 0));-> (+ D C B A)
(Function '(- 2 3 4 5 6));-> -19
(Function '(- 1 B));-> (- 1 B)
(Function '(- 6 2 A B 3 C));-> (- 1 C B A)

In any Lisp you have car to fetch the first element of a list and cdr for fetch the list without the first element and cons to add a list to the beginning of another list.
identify the operation by looking at the first element. Since - in a quoted list is a symbol you cannot apply this so you need to have a list of acceptable operations.
Loop through the rest of the list accumulating the non numbers to a list and the numbers using the operation.
cons the resulting number onto the list of symbols, then the operation making it (op num . symbols)
I'm assuming that + and - don't work as math as swithcing the order when using - or any other non associative operation changes the result.

Related

setf seems to change both its arguments when they are given by aref

In Lisp, I've defined an array a and then let b be equal to a. I now want to redefine an entry of b to be equal to a different entry in a, like this:
(setf a (make-array '(2 2) :initial-contents '((1 2) (3 4))))
(setf b a)
(setf (aref b 0 0) (aref a 0 1))
So now, b will be #2A((2 2) (3 4)), which is all well and good. But what puzzles me is that a is also now #2A((2 2) (3 4)).
My question is this: why has applying setf to an entry of b changed a as well? I can get around this by introducing an intermediate variable with (setf x (aref a 0 1)) and then applying (setf (aref b 0 0) x), but this seems like a strange workaround to me.
Your (setf b a) in the second line does what is sometimes called a shallow copy in other languages. That is, b does not become an independent copy of the array a, but rather becomes just another name for the exact same array. As a result, when you modify b, you are modifying a as well.
If you want b to be a true, independent copy ("deep copy") of the array, then you'll need to allocate a new array and copy the elements of a into it. One way to do this is for 1-dimensional arrays is with the copy-seq function. For fancier arrays you might also look at this question about how to copy 2d arrays which talks about some available libraries and approaches.

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.

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.

Problems with Nth in common lisp

I'm trying to write a function that can calculate GPA. Now I can do limited calculation(only 3 ),but I stuck on how to calculate more , without using loop or recursion (that's the requirement of subject) how to expend nth function? like: (nth n) ,if so ,is that mean i need to write a lambda expression? As an newbie, I maynot describe the question clearly, really need some help..
Glist is grade points Clist is credit hours.
GPA=( gradepoint *credithour + gradepoint *credithour) / ( the sum of credithour) like: (3*1+3*2+4*1)/(1+2+1)
here is my code:
(defun gpa (Glist Clist)
(format t "~3,2f~%"
(/
(+(nth 0 (mapcar #' * Glist Clist))
(nth 1 (mapcar #' * Glist Clist))
(nth 2 (mapcar #' * Glist Clist)))
(+ (nth 0 Clist)
(nth 1 Clist)
(nth 2 Clist))
);end "/"
);end "format"
(values) );end
EDIT
This seems like a good opportunity to emphasize some common (little c) Lisp ideas, so I fleshed out my answer to illustrate.
As mentioned in another answer, you could use a sum function that operates on lists (of numbers):
(defun sum (nums)
(reduce #'+ nums))
The dot product is the multiplicative sum of two (equal-length) vectors:
(defun dot-product (x y)
(sum (mapcar #'* x y)))
The function gpa is a simple combination of the two:
(defun gpa (grades credits)
(/ (dot-product grades credits) (sum credits)))
The example from the question results in the answer we expect (minus being formatted as a float):
(gpa '(3 3 4) '(1 2 1))
> 13/4
There are a few things worth mentioning from this example:
You should learn about map, reduce, and their variants and relatives. These functions are very important to Lisp and are very useful for operating on lists. map* functions generally map sequences to a sequence, and reduce usually transforms a sequence into to a single value (you can however use forms like (reduce #'cons '(1 2 3))).
This is a good example of the "bottom-up" approach to programming; by programming simple functions like sum that are often useful, you make it easy to write dot-product on top of it. Now the gpa function is a simple, readable function built on top of the other two. These are all one-liners, and all are easily readable to anyone who has a basic knowledge of CL. This is in contrast to the methodology usually applied to OOP.
There is no repetition of code. Sure, sum is used more than once, but only where it makes sense. You can do very little more to abstract the notion of a sum of the elements of a list. It's more natural in Scheme to write functions with functions, and that's a whole different topic. This is a simple example, but no two functions are doing the same thing.
If you're using nth to traverse a list, you're doing it wrong. In this case, you might want to write a summing function:
(defun sum (items)
(reduce #'+ items))