newLISP Fan Club

Forum => Anything else we might add? => Topic started by: pjot on April 05, 2008, 11:44:38 PM

Title: Adding values to the same variable
Post by: pjot on April 05, 2008, 11:44:38 PM
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
Title:
Post by: Lutz on April 05, 2008, 11:49:11 PM
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
>
Title:
Post by: pjot on April 05, 2008, 11:52:36 PM
OK, and of course now the inevitable question: what about the other operators? ;-)
Title:
Post by: pjot on April 06, 2008, 12:01:56 AM
...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'?
Title:
Post by: newdep on April 06, 2008, 12:10:41 AM
you want smaler code?



you dont like => (push srt <text> -1)  ?
Title: Re: Adding values to the same variable
Post by: cormullion on April 06, 2008, 01:14:44 AM
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
Title:
Post by: Lutz on April 06, 2008, 01:37:18 AM
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.
Title:
Post by: pjot on April 06, 2008, 01:44:32 AM
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