Page 1 of 1

delayed evaluation of arguments

Posted: Wed Feb 17, 2010 10:46 pm
by Betelgeuse
Suppose you make a lambda function with several arguments sometimes you don't want to use all those arguments. There is a way to make that code faster by not evaluating all of the arguments.

Here is a silly example.

Code: Select all

(setq oddEvenMulti (lambda (a %b %c)
	(if (eq 1 (modulo a 2))
		(multiply a (eval %b))
		(multiply a (eval %c))
	)
))
As you can see I used % to stop the evaluation until I wanted it. You may ask how would this help?

Consider the case

Code: Select all

(oddEvenMulti (objGetData gplayership "numb") (objGetData (item (sysFindObject gPlayerShip "G") 0) "numb") (objGetData (item (sysFindObject gPlayerShip "G") 1) "numb"))
Now you will never use both stargates so are you using an extra sysFindObject (it is an expensive function), objGetData, and item if you did not use delayed evaluation. This could save you lots of time overall and would make your function more friendly to complex arguments.

Posted: Wed Feb 17, 2010 10:54 pm
by alterecco
Another case for this is for default values. I have this function I use sometimes:

Code: Select all

(setq extSelect (lambda (test val) (if test test val)))

;; I use something like this to determine some positions
(setq pos (extSelect (find somelist element) (count somelist)))
The only problem is that (count somelist) is always evaluated, making this slow in some cases. This can now be rewritten like this:

Code: Select all

(setq extSelect (lambda (test %val)
  (if test test (eval %val))
))
Much better :D

Posted: Sun May 30, 2010 2:32 pm
by Prophet
While reading some common Lisp tutorials online on found some information that is relevant.
The true power of the ' ! (single quote)

The ' character flips the interpreter into read only mode:
(add 1 1)
is normally a function call and the interpreter will treat the first parameter as a function.
'(add 1 1)
is now a list with a string and 2 integers.

So what does that mean?

You can store a function in a variable and use it, modify or whatever you want, whenever you want.

(setq myVar '(add 1 1))
currently myVar is a list with 3 elements,
(eval myVar) returns 2

(lnkAppend myVar 5))
returns the list (add 1 1 5)
and
(eval myVar) now returns 7