Adding values to the same variable

Started by pjot, April 05, 2008, 11:44:38 PM

Previous topic - Next topic

pjot

Hi,



In some languages (C, AWK, Scriptbasic) it is possible to add a value to the same variable like this:

value+=5


This actually means 'value = value + 5'.



In newLisp this has to be written as:

(set 'value (+ value 5))


Can we have maybe a new operator like '+=', '-=' and so on, so these type of calculations can be written as  follows:

(set 'value (+= 5))

- or even better:

(+= 'value 5)


What do you think?



Peter

Lutz

#1
for + and - we have already inc and dec:


> (set 'x 0)
0
> (inc 'x)
1
> (inc 'x)
2
> (inc 'x 2)
4
> (inc 'x 2)
6
> (dec 'x 3)
3
> (dec 'x 3)
0
>

pjot

#2
OK, and of course now the inevitable question: what about the other operators? ;-)

pjot

#3
...and also, how about strings?



Now we need to append like this:

(set 'str "0123")
(set 'str (append str "4567"))


How about something like:

(set 'str "0123")
(app 'str "4567")


So the 'app' behaves like an 'inc'?

newdep

#4
you want smaler code?



you dont like => (push srt <text> -1)  ?
-- (define? (Cornflakes))

cormullion

#5
Quote from: "pjot"

value+=5

This actually means 'value = value + 5'.


Personally I'd rather see the latter than the former, and it looks better in Lisp form too - (set 'value (+ value 5)). It's more readable - although I'll agree it's a bit more typing.



Perhaps this is a good reason for writing macros to develop your preferred set of shorthand operators...


(define-macro (scale s x)
   (set s (mul (eval s) x)))
   
(set 'a 12)
(scale a 2)
24

Lutz

#6
Then there is also this for destructive string append:


> (set 'str "123")
"123"
> (write-buffer str "456")
3
> str
"123456"
>


When you give 'write-buffer' a string instead of a file handle, it appends to it.

pjot

#7
Thanks for the answers.
Quote
Personally I'd rather see the latter than the former, and it looks better in Lisp form too - (set 'value (+ value 5)). It's more readable - although I'll agree it's a bit more typing.


It's not a matter of typing, but rather shortness and elegance of code. Contrary to Cormullion, I find the '(set 'value (+ value 5))' not very elegant, but it's a matter of taste, I guess :-)



Peter