Return Statements - Spicery/Nutmeg GitHub Wiki

The return statement in Nutmeg will be a bit of a surprise to programmers coming from languages such as C#, Java, Python or Javascript (to name a few). It is a bit like a combination of return and throwing depending on the context.

As the Last Statement (and without options)

It may appear as the last statement in a procedure and look like this - note that the parentheses are mandatory.

    return( EXPRESSION )

In this case it means that the return expression is the only value to be returned from the procedure. In other words, any other results that were accumulating are to be discarded. This usage of the return statement should feel comfortable to most programmers.

It is important to note that a return statement without options can only appear as the final statement of a procedure.

### Product of a list of numbers
def product( list ):
    var sofar := 0
    for i in list:
        sofar <- sofar + 1
    endfor
    return( sofar )
end

With Options

When a return statement is used elsewhere in a procedure, it must be used with an option e.g.

def find( A ):
    for i in A:
        if isAnswer( i ) return Found( i ) end
    endfor
    return NotFound()
end

A return statement with an option can be used anywhere, including the last statement position, as shown. And it also means that any other results accumulated so far should be discarded. However the calls to the procedure should now be matched e.g.

try find( A ) 
case Found( Ai ) then Ai
case NotFound() then null
end

If a procedure's return is not immediately handled then this causes an exception.

Now this probably all seems a bit strange if you have come from other programming languages. However, Nutmeg has additional constructs that makes the usual meaning of return almost wholly redundant. What is useful, though, is the ability to distinguish 'happy' from 'unhappy' paths. The return-with-option corresponds to an unhappy path and the optionless-return is normally used for the happy path.

Code that calls a function that uses return-options has the responsibility of handling both happy and unhappy paths. If the caller ducks that responsibility, the runtime-system takes over by raising an exception, which must be caught rather than handled.

Conditional Returns

Return statements are commonly guarded by an if. Consequently there is a specialised form for a combined if/return pair.

def find( A ):
    for i in A:
        return Found( i ) if isAnswer( i )
    endfor
    return NotFound()
end

As you might expect, there is an ifnot variant.

def find( A ):
    for i in A:
        return Found( i ) ifnot isIrrelevant( i ) 
    endfor
    return NotFound()
end

It is recommended that this form is only used when the statement conveniently fits on a single line.