Does a recursive function require a return value outside the if statement - function

My code goes something like this:
string my_function(string input)
{
if (sentinel reached)
{
return output;
}
else
{
//do something to change the string and get closer to the sentinel
my_function(input);
}
}
As you can see it is a recursive function that checks if a sentinel value has been reached at which point it returns the output of the function. If it hasn't, it performs some manipulation on the string, then executes itself in recursion.
Since I have a return function in the if statement, and the function will always get to that point, do I need a return after the else statement. It seems unnecessary since that return statement will never execute.

You do need a return clause, but it should be return my_function(input) within the else branch otherwise the final result obtained when the sentinel is reached will not be available as the stack is unwound back to the original call.

If you programmed the recursion well enough so that the sentinel eventually
is reached, then some call to this function will get to the "if" branch
of the "if" statement.
But if the function actually needed recursion, that is, if the sentinel
was not already true before the very first time this function was called,
then the first call to the function will execute the "else" clause and then
... what? The function is supposed to return something, but you don't
say what to return.
The fact that during the recursion in the "else" clause, some other
(recursive) call to this same function executed the "if" clause,
does not tell the first call to the function what to do. It can only do
what you literally told it to.
Edit: The code will compile, but it will not return a meaningful value
if even one level of recursion occurs. Your compiler might issue a warning
about the lack of the return value, which you should heed.

Related

How to understand the introduction of Promise.resolve in the reduce method of Array

const tasks = [f1, f2, f3];
tasks.reduce(async (promise, task) => {
await promise;
await task();
}, Promise.resolve)
1、The role of Promise.resolve
2、The role of await promise;
Thanks~~
This design pattern using .reduce() is to serialize a number of promise-returning operations. As such, the logic is that you wait on the previous promise, then when it's done you execute your next task and return a promise as value for the next cycle through the loop where the process can be repeated.
To make that first iteration work without special code for the first iteration, you need a promise that you can initially wait for. So, you pass an already resolved promise created with Promise.resolve() to "prime the pump" and give it an initial promise to use.
If you unwrap the .reduce() loop, in your example, you essentially end up with this:
Promise.resolve().then(f1).then(f2).then(f3)
Starting the chain with Promise.resolve() avoids special casing the first iteration of the loop.
That could be written as:
f1().then(f2).then(f3)
But, that special cases the first task which really complicates using something like .reduce() which is simplest when you do the same thing with every iteration of the loop. So, starting things off with Promise.resolve() allows the first iteration to do exactly the same thing as all the other iterations.
As for your two bullet points:
The role of Promise.resolve()
To give .reduce() an initial promise for the first iteration to wait for.
The role of await promise
That waits until the task from the previous iteration of the loop is done before calling the next task.
Note: To fully understand this code, you have to fully understand how .reduce() works. You pass it two arguments, your callback function and an initial value. That initial value is passed to the first iteration of the callback as the first argument to the callback (what you named promise).
Then, whatever value you return from that callback will be passed as the value to the next iteration of the callback. Since you're using an async callback which ALWAYS
returns a promise, your callback will always return a promise which is what will get passed to the next iteration of the callback. And, because the first thing your callback does is await promise, you end up "chaining" promises which serializes the execution of your tasks.

Why a lambda cannot make the enclosing function return?

I'm quite new to Kotlin. I hit this part while I was going over the docs:
"a lambda cannot return from the enclosing function" (unless it's inlined).
So, this doesn't work;
fun foo() {
ordinaryFunction {
return // ERROR: cannot make `foo` return here
}
}
I wonder why it works that way?
The only thing I can think of it's dangerous since there might be some extra stuff the enclosing function might be doing after the lambda execution. But I'm not sure that's the reason because you can overcome this by using qualified returns or using inline keyword. So, that kind of implies there's a technical reason behind it (apart from any usability/safety reasons) like the compiler cannot figure out where to return unless it's labeled or inlined.
Any help would be great!
The problem is here that non-local returns can't be done on the JVM.
If you want to return from lambda (local return) you can add label #ordinaryFunction:
fun foo() {
ordinaryFunction {
return#ordinaryFunction
}
}
Docs say:
If we need to return from a lambda expression, we have to label it and qualify the return. Oftentimes it is more convenient to use implicit labels: such a label has the same name as the function to which the lambda is passed. In our case it is #ordinaryFunction.
Someone else can probably explain this better but in pretty much any programming language, when you call a function, a new entry is created on top of the stack. The stack keeps information about the arguments that the function was called with and the place you should return to when the function completes.
Kotlin doesn't have a feature that lets you return from multiple function calls in one return, so you have to return from each function call manually.
When you inline a function the machine code that would normally execute in a separate subroutine is now copy pasted to the function call site instead. That's why return from an inline function actually returns from the function that called the inlined lambda.
there might be some extra stuff the enclosing function might be doing after the lambda execution.
The problem is the other way around: the lambda can "escape" from the enclosing function's scope and end up executing after the function returns. E.g. consider
fun foo() {
Thread(Runnable {
Thread.sleep(1000)
return
})
}
Or just
fun foo() = // lambda
In either case it makes no sense for the lambda to return from foo, does it? And the compiler doesn't know if your ordinaryFunction lets the lambda escape foo's scope unless it's inline.
you can overcome this by using qualified returns
That's not really overcoming, that's just not returning from the enclosing function.

Which method for handling conditions inside a function would be the most practical?

What's fastest, safest, and most practical way of handling conditions inside a function where a condition match must be passed before the function can proceed with any code at all? Below I have a function that returns on condition failure, and another function that only checks for the condition success:
function x()
{
if ( !condition ) return;
[code]
}
Or
function y()
{
if ( condition )
{
[code]
}
}
McCabe's cyclomatic complexity punishes functions with more than one return statement. I guess to provide a formalism that supports structured programming (one entry point for each function/"Goto Statement Considered Harmful") taken to the extreme, i.e. one exit point for each function.
Reducing the number of return statements in a function reduces the number of break-points to insert in a debugging situation where the final values of function local variables are to be inspected.
If your development method involves frequent use of a debugger you could argue for using the y() approach.

Where is the return value of a function stored?

I assume this question is language agnostic, and apologies if it's quite rudimentary, but say we have (PHP in this example)
function myFunc() {
return 4;
}
Now when this function is called, usually the result will be used in an expression or be assigned to a variable. But if it's not assigned to a variable, where does the return value "live" when it's been called? Is there an internal structure that keeps it in memory for the purpose of the current statement, and when that statement is executed, it removes it again?
If you just do something like:
var foo = bar();
myFunc();
var wibble = baz();
Then a Number 4 will be created for the return statement, then immediately will be discarded as there aren't any references to it.
(Note: C++ specific) In most cases compiler will user Return Value Optimisation and store value in the variable that gets the result of the function assigned to.
For example:
int myInt = myFunc();
will cause the pointer to myInt varaible to by passed to myFunc on the stack so myFunc will work directly with myInt without creating a new variable.
Otherwise the function returns by placing the return value on the stack.
I think in .NET it's called Name Return Value Optimization.
Other compilers probably have similar features in place.
so say we had a more complex statement like myFunc() + ComplexFunction()
I think this one depends on the compiler and it's register allocation scheme.
The compiler could store the result for myFunc() in a register, then jump to execute ComplexFunction(). On entering ComplexFunction(), the registers would be saved on the stack and the restored when returning.

Best Practice: function return value or byref output parameters?

I have a function called FindSpecificRowValue that takes in a datatable and returns the row number that contains a particular value. If that value isn't found, I want to indicate so to the calling function.
Is the best approach to:
Write a function that returns false if not found, true if found, and the found row number as a byref/output parameter, or
Write a function that returns an int and pass back -999 if the row value isn't found, the row number if it is?
Personally I would not do either with that method name.
I would instead make two methods:
TryFindSpecificRow
FindSpecificRow
This would follow the pattern of Int32.Parse/TryParse, and in C# they could look like this:
public static Boolean TryFindSpecificRow(DataTable table, out Int32 rowNumber)
{
if (row-can-be-found)
{
rowNumber = index-of-row-that-was-found;
return true;
}
else
{
rowNumber = 0; // this value will not be used anyway
return false;
}
}
public static Int32 FindSpecificRow(DataTable table)
{
Int32 rowNumber;
if (TryFindSpecificRow(table, out rowNumber))
return rowNumber;
else
throw new RowNotFoundException(String.Format("Row {0} was not found", rowNumber));
}
Edit: Changed to be more appropriate to the question.
functions that fail should throw exceptions.
If failure is part of the expected flow then returning an out of band value is OK, except where you cannot pre-determine what an out-of-band value would be, in which case you have to throw an exception.
If I had to choose between your options I would choose option 2, but use a constant rather than -999...
You could also define return value as Nullable and return Nothing if nothing found.
I would choose option 2. Although I think I would just use -1 not -999.
Richard Harrison is right that a named constant is better than a bare -1 or -999.
I would go with 2, or some other variation where the return value indicates whether the value was found.
It seems that the value of the row the function returns (or provides a reference to) already indicates whether the value was found. If a value was not found, then it seems to make no sense to provide a row number that doesn't contain the value, so the return value should be -1, or Null, or whatever other value is suitable for the particular language. Otherwise, the fact that a row number was returned indicates the value was found.
Thus, there doesn't seem to be a need for a separate return value to indicate whether the value was found. However, type 1 might be appropriate if it fits with the idioms of the particular language, and the way function calls are performed in it.
Go with 2) but return -1 (or a null reference if returning a reference to the row), that idiom is uses extensively (including by by .nets indexOf (item) functions), it's what I'd probably do.
BTW -1 is more acceptable and widly used "magic number" than -999, thats the only reason why it's "correct" (quotes used there for a reason).
However much of this has to do with what you expect. Should the item always be in there, but you just don't know where? In that case return the index normally, and throw an error/exception if it's not there.
In this case, the item might not be there, and that's an okay condition. It's an error trap for unselected values in a GridView that binds to a datatable.
Another few possibilities not yet mentioned:
// Method 1: Supports covariance; can return default<T> on failure.
T TryGetThing(ref bool success);
// Method 2: Does not support covariance, but may allow cleaner code in some cases
// where calling code would use some particular value in in case of failure.
T TryGetThing(T DefaultValue);
// Method 3: Does not support covariance, but may allow cleaner code in some cases
// where calling code would use some particular value in case of failure, but should
// not take the time to compute that value except when necessary.
T TryGetThing(Func<T> AlternateGetMethod);
// Method 4: Does support covariance; ErrorMethod can throw if that's what should
// happen, or it can set some flag which is visible to the caller in some other way.
T TryGetThing(Action ErrorMethod);
The first approach is the reverse of the method Microsoft developed in the days before support existed for covariant interfaces. The last is in some ways the most versatile, but is likely to require the creation of a couple of new GC object instances (e.g. a closure and a delegate) each time it's used.