I wonder if there is some function/macro in Common Lisp has similar function as *= or /= operation in C/C++.
incf and decf in Common Lisp can be considered as += and -=.
In C/C++
A *= 2;
equals to
A = A * 2;
In Common Lisp
When I want to set a new value to an array element, I have to write as
(setf (aref arr i) (* (aref arr i) 2))
The statement of accessing the array has to write two times, if there is a function/macro mulf have similar function as *= in C language.
I can write code as
(mulf (aref arr i) 2)
Then the array accessing statement is needed to write only once.
Thanks.
As stated in the comments, this can easily be created using DEFINE-MODIFY-MACRO.
(define-modify-macro mulf (x) *)
Not in the standard either, but it seems the zap macro is here for that. For example:
(zap #'+ x 5)
Here is the suggested implemantion:
(defmacro zap (fn place &rest args)
(multiple-value-bind
(temps exprs stores store-expr access-expr)
(get-setf-expansion place)
`(let* (,#(mapcar #'list temps exprs)
(,(car stores)
(funcall ,fn ,access-expr ,#args)))
,store-expr)))
Related
Is recursion the only way to write something like a for-loop in the Racket dialect sdp ("Schreibe dein Programm!"), in which "(for)" isn't a thing or is there a more "efficient" or simpler way to do so?
What would the closest equivalent to the C++ loop for(i = 0 , i < 100, i++) look like in Racket-sdp code?
How I did this up until now was:
(: my-loop (natural -> %a))
(define my-loop
(lambda (i)
(cond
[(< i 100) (my-loop (+ i 1))] ; <-- count up by one till 99 is reached
[else "done"] ; <-- end
)))
(my-loop 0)
EDIT:
It's more of a general question. If I were to write lets say a raket library which contains a general function, that might be used like this:
(for 0 (< i 100) (+ i 1) (func i))
in my programs which is a for-loop that runs with a given function as it's "body", would there be a way to implement this properly?
[Professor of the mentioned course here.]
Recursion indeed is the only way to express iterated computation in the Racket dialect we are pursuing. (Yes, that's by design.)
Still, higher-order functions (and recursion) provide all you need to create your own "loop-like control structures". Take the following HOF, for example, which models a repeat-until loop:
(: until ((%a -> boolean) (%a -> %a) %a -> %a))
(define until
(lambda (done? f x)
(if (done? x)
x
(until done? f (f x)))))
Note that the until function is tail-recursive. You can expect it to indeed behave like a loop at runtime — a clever compiler will even translate such a function using plain jump instructions. (We'll discuss the above in the upcoming Chapter 12.)
You can make a high-order for-loop.
Here is an simple example:
(define (for start end f)
(define (loop i)
(when (< i end)
(f i)
(loop (+ i 1))))
(loop start))
(for 0 10 (λ (i) (displayln i)))
You can make this more general if you use a next function instead of (+ i 1) and use a while-predicate? function instead of (< i end).
I have the following function:
(defun transform-matrix (matrix)
(let ((res (map 'vector
(lambda (x)
(map 'vector
(lambda (ix)
(if ix
'(t 0) ; --> Problem happens here
0))
x))
matrix)))
res))
This function will accept a 2d matrix, in which each element can either be t or nil. Then it will transform t -> '(t 0) and nil -> 0.
The result array has one problem is every (t 0) cons now point to the same memory location. For example if i save the result array in res variable and do this:
(eq (aref (aref res 0) 0)
(aref (aref res 1) 1))
*Assume that res[0][0] and res[1][1] is the '(t, 0) nodes.
This will result in T. But do like this is result in nil:
(eq '(t 0) '(t 0))
Can i ask what happen with the transform-matrix that make created cons to point to the same memory location.
I test these codes on SBCL 2.0.0 Windows 64 Bit.
Thank you.
One way to see the problem here is to change your function to this:
(defun transform-matrix (matrix)
(let ((non-nil-value '(t 0))
(nil-value 0))
(map 'vector
(lambda (x)
(map 'vector
(lambda (ix)
(if ix non-nil-value nil-value))
x))
matrix)))
It should be clear that this code is functionally identical: both functions have a single occurrence of '(t 0): this one just gives it a name.
But now let's gut this function and consider this:
(defun ts ()
(let ((non-nil-value '(t 0)))
(eq non-nil-value non-nil-value)))
Well, certainly I would expect the result of calling this function to be t.
And that's why every element in your resulting nested vectors which isn't 0 is the same: because you only ever constructed one object.
If you want all of the objects in the returned value to be different objects (ie not to be identical), you need to construct a new object each time, for instance by:
(defun transform-matrix (matrix)
(let ((non-nil-template '(t 0)))
(map 'vector
(lambda (x)
(map 'vector
(lambda (ix)
(if ix (copy-list non-nil-template) 0))
x))
matrix)))
This will ensure that each non-zero element of the resulting object
is distinct;
can safely be mutated.
Neither of these were previously true.
For the case of (eq '(t 0) '(t 0)) you might expect that this must return nil. That is (I think definitely) the case in interpreted code. But for compiled code the answer is not so clear. At least for the file compiler, it's fairly clear that in fact this may return t. Section 3.2.4.4 of the spec says, in part
If two literal objects appearing in the source code for a single file processed with the file compiler are the identical, the corresponding objects in the compiled code must also be the identical. With the exception of symbols and packages, any two literal objects in code being processed by the file compiler may be coalesced if and only if they are similar; if they are either both symbols or both packages, they may only be coalesced if and only if they are identical.
And in (eq '(t 0) '(t 0)), there are two literal lists, which are similar, and which therefore may be coalesced by the file compiler.
As a general rule, if you want a mutable object, or an object which you need to be certain is not identical to any other object, you should construct it explicitly: it is never safe (or even legal) to mutate literal objects, and the rules on which objects can be coalesced are complex enough that it is generally just safer to construct the objects so you know what is happening.
As an aside is there a reason you are using nested vectors rather than a two-dimensional matrix?
Just to add to TFB:
Lisp does not copy its arguments in a function call. It passes references to it:
(let ((a '(1 2))) ; A is a reference to (1 2)
(foo a) ; calls FOO and the same (1 2) will be
; accessible via a new reference inside FOO
(setf (aref array 0) a)
(setf (aref array 1) a) ; this will make the array at 0 and 1
; reference the same list
)
If i use the quote version '(t 0) twice in the REPL i still can get two different cons.
That's because in the REPL you would need to enter '(t 0) twice and make sure that the Reader (the R in REPL) constructs new lists, which it usually does:
CL-USER > (eq (read) (read))
(0 1) (0 1)
NIL
Now the REPL reader:
CL-USER 6 > '(1 2)
(1 2) ; result
CL-USER 7 > '(1 2)
(1 2)
CL-USER 8 > (eq * **) ; comparing previous results
NIL
Each call to READ conses a fresh new lists.
Side note: There are actually also more advanced REPL readers, where one can reference already existing lists, like in the REPL of the McCLIM listener.
Firstly, note that your transform-matrix function contains exactly one instance of the '(t 0) syntax, whereas the expression you're testing at the REPL contains two instances: (eq '(t 0) '(t 0)).
Because that expression has two instances, it is is possible that those will be different objects. In fact, the Lisp implementation would have to go out of its way to turn them into one object, and it is something that is allowed.
The (t 0) syntax is a piece of the program's source code. A program can apply the quote operator (for which the ' character is a shorthand) to a piece of its syntax to use that syntax as a literal. A given literal is one object; multiple evaluations of the same quote yield the same object.
When Lisp is naively interpreted, the interpreter recursively walks the original list-based source code. The implementation of the quote operator simply returns the piece of code that is being walked as a value.
When Lisp is compiled, the list-based source code is transformed to something else, such as native machine language for the CPU to execute directly. In the transformed image, the source code is gone. Yet, the compiler has to recognize the quote special form and translate it somehow. To do that, it has to take the piece of source code structure enclosed by quote and embed that object in the compiled image, so that it's somehow available to the compiled code: i.e. that quoted part of the source is not gone, but is propagated into the translation. For instance, the compiled image may be accompanied by a static vector dedicated for storing literals. Whenever the compiler process a quote expression like '(t 0), it allocates the next available slot in that vector, like position 47 or whatever, and stick the object (t 0) into that slot. The compiled version of '(t 0) code will then access that slot 47 in the literal data vector, and it will do that every time it is executed, retrieving the same object each time, just like the interpreted version of the program retrieveds the same piece of its own source code each time.
When compiling literals, the compiler may also search through the vector and de-duplicate it. Instead of allocating the next available index, like 47, it might scan through the literals and discover that index 13 already has a (t 0). Then it generates code to access index 13. Therefore, the compiled version of (eq '(t 0) '(t 0)) may well yield true.
Now, the way your question is framed, there is no evidence that there is an actual problem from all of the slots sharing a single instance of (t 0).
You need these objects to be different if you ever change the 0 value to something else by mutation. However, even that issue can be solved without actually making the objects different up-front. So that is to say, we can keep all the (t 0) entries objects pointing to the same object, and if we want to change some of them to, say, (t 3), we can allocate a whole new object at that time, rather that doing (set (cadr entry) 3). Moreover, maybe we can make all the (t 3) entries point to a single (t 3), like we did with (t 0).
It is impossible to say that changing '(t 0) to (list t 0) is the best approach to fix the problem, assuming there even is a problem.
I am writing a Greatest Common Factor function.
I kept getting errors saying
"(if t (set q).....)" is not valid syntax
and so I commented it out. But then I was told that my do syntax is invalid.
syntax error on the 'do' clause
But I'm looking at it and seeing no errors. Why will my code not work?
(defun myGCD (a b)
"My function, which returns the Greatest Common Factor"
(let ((x a) (y b) (z 0))
(loop until (or (zerop x) (zerop y))
do ( ;(progn
;(if t ;(< a b)
; If case
;((setq b (- b a)) (setq c a))
; Else case
;((setq a (- a b)) (setq c b))
;)
;(return c)
);)
)
)
)
(myGCD 10 20)
You have basic syntax errors in your code.
In a LOOP form you need to have one or more compound forms after a DO.
(loop ... do () )
is not allowed, because () is not a compound form.
Also note that parentheses are not grouping expressions in a sequence.
((foo 1) (bar 2))
above is not valid Lisp. In Scheme it might be correct, but there the first form then needs to return a function.
To group expressions you would need something like progn, which allows embedded forms and returns the values of the last one:
(progn
(foo 4)
(bar 2))
Above is valid.
As it turns out, you can't have an empty 'do' command. This doesn't explain why the other logic was failing, but I will look at that some more.
I'm trying to wrap my head around Elisp's cl-loop facility but can't seem to find a way to skip elements. Here's an artificial example to illustrate the problem: I'd like to loop over a list of integers and get a new list in which all odd integers from the original list are squared. The even integers should be omitted.
According to the documentation of cl-loop, I should be able to do this:
(loop for i in '(1 2 3)
if (evenp i)
append (list)
else
for x = (* x x)
and append (list x))
The desired output is '(1 9) instead I get an error:
cl--parse-loop-clause: Expected a `for' preposition, found (list x)
Apparently the and doesn't work as expected but I don't understand why. (I'm aware that I could simplify the else block to consist of only one clause such that the and isn't needed anymore. However, I'm interested in situations where you really have to connect several clauses with and.)
Second part of the question: Ideally, I would be able to write this:
(loop for i in '(1 2 3)
if (evenp i)
continue
for x = (* x x)
append (list x))
Continue is a very common way to skip iterations in other languages. Why doesn't cl-loop have a continue operator? Is there a simple way to skip elements that I overlooked (simpler than what I tried in the first example)?
In Common Lisp it is not possible to write such a LOOP. See the LOOP Syntax.
There is a set of variable clauses on the top. But you can't use one like FOR later in the main clause. So in an IF clause you can't use FOR. If you want to introduce a local variable, then you need to introduce it at the top as a WITH clause and set it later in the body.
(loop for i in '(1 2 3)
with x
if (evenp i)
append (list)
else
do (setf x (* i i))
and append (list x))
LOOP in Common Lisp also has no continue feature. One would use a conditional clause.
Note, that Common Lisp has a more advanced iteration construct as a library ITERATE. It does not exist for Emacs Lisp, though.
You could do:
(loop for i in '(1 2 3)
if (oddp i) collect (* i i))
That would solve your sample problem.
And here's another without loop (yes, I know you asked for loop):
(let ((ns ()))
(dolist (n '(1 2 3))
(when (oddp n) (push (* n n) ns)))
(nreverse ns))
And without even cl-lib (which defines oddp):
(let ((ns ()))
(dolist (n '(1 2 3))
(unless (zerop (mod n 2)) (push (* n n) ns)))
(nreverse ns))
Everything about such definitions is clear -- just Lisp. Same with #abo-abo's examples.
loop is a separate language. Its purpose is to express common iteration scenarios, and for that it can do a good job. But Lisp it is not. ;-) It is a domain-specific language for expressing iteration. And it lets you make use of Lisp sexps, fortunately.
(Think of the Unix find command -- similar. It's very handy, but it's another language unto itself.)
[No flames, please. Yes, I know that dolist and all the rest are essentially no different from loop -- neither more nor less Lisp. But they are lispier than loop. Almost anything is lispier than loop.]
Here's a loop solution:
(loop for i in '(1 2 3)
when (oddp i) collect (* i i))
Here's a functional solution:
(delq nil
(mapcar (lambda(x) (and (oddp x) (* x x)))
'(1 2 3)))
Here's a slightly different solution (be careful with mapcan - it's destructive):
(mapcan (lambda(x) (and (oddp x) (list (* x x))))
'(1 2 3))
I am trying to create a copy of the first element in the array and add the copy to the end of the array. I then want to do work (move_NE) on the copy I just created, changing it but not the original. The intended result is to have an array of two elements, one which points to the original and the other which points to a modified original.
(vector-push-extend (initialize_board 5) *all_states*)
(vector-push-extend (elt *all_states* 0) *all_states*)
(move_NE (elt *all_states* 1) 0 2)
From what I can figure, (elt *all_states* 0) is producing a reference to the original element which results in an array with two elements, both which point to the same thing.
The context of this program is from my attempts to write a program to generate all possible moves for a triangular peg solitaire (cracker barrel) game. *all_states* is an array of boardstates, each of which are a 2d array.
Any help is appreciated.
EDIT: My background is in C/C++ programming.
There's no copying-on-assignment in Common Lisp. (And, as far as I'm aware, There's not in most Object Oriented Programming languages, either. E.g., in Java, if you have Object x = ...; Object y = x; there's just one object. If you modify that object through either the variable x or y, the change will be visible if you access the object through the other variable.) If you need a copy of an object, you'll need to make that copy yourself. That's just the same for other built in datatypes, too.
First, note that if you store a value in an element of an array, it doesn't modify the previous value that was stored in that array:
CL-USER> (let ((a (make-array 10 :adjustable t :fill-pointer 1)))
(setf (aref a 0) "one")
(print a)
(vector-push-extend (aref a 0) a)
(print a)
(setf (aref a 1) "five")
(print a))
; #("one")
; #("one" "one")
; #("one" "five")
But, when the array looked like #("one" "one"), the value of (aref a 0) and (aref a 1) is the same string. You can see this if we modify that string:
CL-USER> (let ((a (make-array 10 :adjustable t :fill-pointer 1)))
(setf (aref a 0) "one")
(print a)
(vector-push-extend (aref a 0) a)
(setf (char (aref a 1) 2) #\3)
(print a))
; #("one")
; #("on3" "on3") ; we changed the **single** string
When you extend the array you can, of course, make a copy of the object, and then there will be two distinct objects:
CL-USER> (let ((a (make-array 10 :adjustable t :fill-pointer 1)))
(setf (aref a 0) "one")
(print a)
(vector-push-extend (copy-seq (aref a 0)) a)
(print a)
(setf (char (aref a 1) 2) #\3)
(print a))
; #("one")
; #("one" "one")
; #("one" "on3")
You mentioned
From what I can figure, (elt *all_states* 0) is producing a reference
to the original element which results in an array with two elements,
both which point to the same thing.
That's really the behavior that you want. If (elt *all_states* 0) didn't return the object at index 0 of the array, but returned a copy of the object, there'd be no way to modify the actual thing that's stored in the array (if the array was the only way to get ahold of the object). You mentioned coming from a C/C++ background; I highly recommend that rather than try to adapt that mental model to become a mental model for Common Lisp, that you spend some time building a mental model of Common Lisp from (almost) scratch. I don't mean that in a dismissive sense; in my opinion, it's good advice for any programmer learning a new language. If you try to "get by" with assumptions based on other languages, you can end up with some pretty subtle and hard-to-find bugs. I'd make a similar suggestion to someone with a Lisp background learning C/C++. If, for some reason, you don't have the time to do that, the quickest and safest advice I can give you is this:
If you you need to think of Common Lisp with a C/C++ model, choose C, not C++. Primitive datatypes (ints, chars, etc.) are roughly the same, and everything is is handled by pointers.
With that model, then your initial problem is very clear. You've got an array of pointers to objects, and you extended an array with another pointer to the same object. It's no surprise, then, that when you modified the object pointed at by that pointer, it was visible through all pointers to that object. You need to allocate a new object that's a copy of the first, and put a pointer to that in the array.
This is really the behavior that you want