andrewducker: (Default)
andrewducker ([personal profile] andrewducker) wrote2010-02-11 03:11 pm

Thinking about code

  If I have a method:
int DoSomething(string someStuff)
{
  //Do Stuff
  return 42;
}
then effectively I have an unnamed variable that gets set by the return statement, yes?

That being the case, wouldn't it be in some ways clearer to have an explicit, named, variable that gets set instead?

int DoSomething(string someStuff)
{
  //Do Stuff
  returnValue = 42;
}

where "returnValue" is a keyword that's used to return the value.

As it is I frequently end up with code that creates (or sets) a variable at various points through the code just so it can be returned at the end.  Making this an explicit part of the language just makes sense to me.

I assume there are languages out there that do this.

[identity profile] nmg.livejournal.com 2010-02-11 04:04 pm (UTC)(link)
Lisp and Scheme do something orthogonal, but related; the value returned by a lambda expression is the value of the last expression evaluated in it.

For example (in Scheme), if we have a function:

(define fib
  (let ((ult 0)(pen 1))
    (lambda ()
      (let ((tmp pen))
        (set! pen (+ ult pen))
        (set! ult tmp)
       ult))))


Each time fib is called, the value returned is that of ult (set! returns an unspecified value).

If we wrote this in Common Lisp instead (where setq returns the value used to set the variable) we could write this instead:

(let ((ult 0) (pen 1))
  (defun fib ()
    (let ((tmp pen))
      (setq pen (+ ult pen))
      (setq ult tmp))))


Here, the value returned by fib is the value of the final setq, which is the value of tmp.
Edited 2010-02-11 16:05 (UTC)