Page 1 of 1

return value in a function

Posted: Sun Apr 02, 2023 10:59 pm
by borisT
I know functions return the result of the last operation
But is there a way to return a value which is not the result of the last operation in a function
.e.g.

Code: Select all

(define (foo)
  (somefunc1...) ; Want to return the result of this function
  (somefunc2...))

Re: return value in a function

Posted: Sun Apr 02, 2023 11:26 pm
by ralph.ronnquist
yes, sometimes one wants the "prog1" function, which can be defined

Code: Select all

(define (prog1 X) X)
Without that you might do it in-line, as

Code: Select all

((fn (X) X) term1 term2 term3 ...)
or

Code: Select all

((list term1 term2 term3 ...) 0)

Re: return value in a function

Posted: Mon Apr 03, 2023 9:38 am
by borisT
Thanks for that, my brain wasn't working! I get it now - use an identity function

Code: Select all

(define (return x) x)

define (foo ..) (
	(setq x (func1...)
	(func2 ....)
	(return x))

Re: return value in a function

Posted: Mon Apr 03, 2023 11:37 am
by ralph.ronnquist
Well if the return value is assigned to a variable it would be enough just mentioning that variable last.

I was seeing it more in line of making the body something like the following, with your "return" function:

Code: Select all

(define (foo ..) 
    (return (func1...) 
	        (func2 ....)
                ...))
The point is that for a lambda function, all the arguments are evaluated whether or not there are function parameters for them. In this case the first arguument value gets assigned to "x" and thus the function, following the evaluations of all arguments, will return that first argument value.

In "traditional Lisp" the "return" function is named "prog1", and it does exactly that; return the value of the first aregument after having evaluated all argument terms. Or Maybe it would be called "begin1" in newlisp since it uses "begin" for the more traditional "prog".

Re: return value in a function

Posted: Mon Apr 03, 2023 1:18 pm
by borisT
The use case I am thinking of is one you often get in GUIs where a handle is returned by e.g. a button create function and then further calls are made with that handle before returning the handle to the caller.

In that use case simply referring to the handle at the end of the function works well
Thanks again for the prompt help