return value in a function

Q&A's, tips, howto's
Locked
borisT
Posts: 6
Joined: Wed Jan 30, 2019 8:39 am

return value in a function

Post 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...))

ralph.ronnquist
Posts: 228
Joined: Mon Jun 02, 2014 1:40 am
Location: Melbourne, Australia

Re: return value in a function

Post 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)

borisT
Posts: 6
Joined: Wed Jan 30, 2019 8:39 am

Re: return value in a function

Post 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))

ralph.ronnquist
Posts: 228
Joined: Mon Jun 02, 2014 1:40 am
Location: Melbourne, Australia

Re: return value in a function

Post 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".

borisT
Posts: 6
Joined: Wed Jan 30, 2019 8:39 am

Re: return value in a function

Post 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

Locked