Why can't I declare a variable or function more than once with different types? - forward-declaration

Okay I know "One Definition Rule", but when I try to declare a variable with different types subsequently in source code, I run into some mistake like following:
int fkc();
void fkc();
enter image description here
I mean these two statements are just two declarations, not definitions. Alright, Does every declaration have to have only one unique definition?

In C++, you can't overload functions based on return type.
Overload resolution takes into account the function name , cv-qualifiers , the number of parameters and their types.
You could do something like:
auto fck()
{
if constexpr(...) return my_int;
else /* do smth without return */
}
but that's not function overloading of course.

Because you cannot overload the method just by changing return type . It is not allowed. The compiler distinguishes function invocations based on signature.and the signature of function includes only function name and arugments like
func(int x....) which does not include return type

Related

what does the brackets after function name do when calling a function in scala?

When reading some scala code, i see something like fooString
but I couldn't find anything that expalins this sort of commands when calling a function.
I know we should define the parameter and expected return type in scala when defining a function or class. Consider this code:
def socketTextStream(
hostname: String,port: Int
): ReceiverInputDStream[String] = withNamedScope("socket text stream") {
socketStream[String](hostname, port, SocketReceiver.bytesToLines)
}
what [String] after "socketStream" do here and I wonder why there is another function( withNamedScope) after "=" here.
First, def socketTextStream(hostname: String, port: Int): ReceiverInputDStream[String] is declaring a method called socketTextStream which receives two inputs (host & port) and returns a ReceiverInputDStream which is a generic class, and in this case the result will be parameterized with the type String.
Then, = withNamedScope("socket text stream") { .. } means that the implementation of that method is call other method (withNamedScope) that takes a String (presumably a name) as its first argument, and a block (probably a by name parameter) as its second argument.
In this case, the two arguments are on separated parameters lists, which is called currying.
Finally, socketStream[String](hostname, port, SocketReceiver.bytesToLines) (which is the body of the block) is calling another method socketStream which is a polymorphic / generic method.
The [String] part is specifying that the type parameter of that method, is String. Maybe this information is redundant or maybe it is used to force an specific implicit, without the definition of such method is hard to tell.
Anyways, all here is basic syntax and structures of the language, all covered by the tour (which many people highlight for being too brief and just covering the basis of the language). Thus, I would recommend you to check more resources before continue with reading code.

I can't figure out how this switch statement is working?

func performMathAverage (mathFunc: String) -> ([Int]) -> Double {
switch mathFunc {
case "mean":
return mean
case "median":
return median
default:
return mode
}
}
I got this example from a swift learning book and its speaking of the topic of returning function types and this is just a part of the whole program I didn't want to copy and paste it all. My confusion is that the book says:
"Notice in performMathAverage , inside the switch cases, we return
either mean , median , or mode , and not mean() , median() , or mode()
. This is because we are not calling the methods, rather we are
returning a reference to it, much like function pointers in C. When
the function is actually called to get a value you add the parentheses
suffixed to the function name. Notice, too, that any of the average
functions could be called independently without the use of the
performMathAverage function. This is because mean , median , and mode
are called global functions ."
The main question is: "Why are we not calling the methods?"
and what do they mean we are returning a reference to it??
What do they mean by reference? Im just confused on this part.
You stated your main question as:
"Why are we not calling the methods?" and what do they mean we are returning a reference to it??
This is a little tricky to grasp at first, but what it's saying is that we don't want the result of the function, we want the function itself.
Sometimes things like this are easier to understand w/ a type alias:
Starting w/ [Int] -> Int, what we're saying there is "a function that takes an array of Ints and returns a single Int"
Let's make a type alias for clarity:
typealias AverageFunction = [Int] -> Int
Now our function (from your example) looks like this:
func performMathAverage(mathFunc: String) -> AverageFunction {
Although, the naming conventions here are pretty confusing since we're not performing anything, instead let's call it like this:
func getAverageFunctionWithIdentifier(identifier: String) -> AverageFunction {
Now it's very clear that this method is functioning like a factory that returns us an average function based on the identifier we provide. Now let's look at the implementation:
func getAverageFunctionWithIdentifier(identifier: String) -> AverageFunction {
switch identifier {
case "mean":
return mean
case "median":
return median
default:
return mode
}
}
So now, we're running a switch on the identifier to find the corresponding function. Again, we're not calling the function because we don't want the value, we want the function itself. Let's look at how we would call this:
let averageFunction = getAverageFunctionWithIdentifier("mean")
Now, averageFunction is a reference to the mean function which means we can use it to get the mean on an array of integers:
let mean = averageFunction([1,2,3,4,5])
But what if we wanted to use a different type of average, say median? We wouldn't have to change anything except for the identifier:
let averageFunction = getAverageFunctionWithIdentifier("median")
let median = averageFunction([1,2,3,4,5])
This example is pretty contrived, but the benefits of this is that by abstracting a function out to it's type (in this case [Int] -> Int, we can use any function that conforms to that type interchangeably.
This is functional programming!
This has to do with the functional programming aspects of swift. Here functions are treated like first class citizens meaning you can treat them like variables.
Why are we not calling the methods?
You are not calling the methods, because you have no argument to apply. The point of the function is to determine which function you would like to use. Of course the name of the function is terrible and does not accurately represent what the function does. It should be more like func determineMathFuncToUse, then you could use it like
var myFunc = determineMathFuncToUse("median")
// Now, you would be able to use myFunc just like you would use median
// e.g. myFunc(some_array) == median(some_array)
This is pretty easy to understand. In Swift you can store references to functions (the closest you can achieve in Objective-C is the reference to block).
func performMathAverage (mathFunc: String) -> ([Int]) -> Double
This is the function whose return type is:
([Int]) -> Double
As you can see the return type of this function is a function which accepts an array of Int and returns Double.
And in code you see that it returns one of three functions: mean, mode, and median. Each of these functions accepts an array of Int and returns Double.
Due to this code below:
let meanFunc = performMathAverage("mean")
let mean = meanFunc(someIntArray)
is identical to:
let mean = mean(someIntArray)
I hope this helps.
The reason why functions are NOT executed in code is because this example illustrates how you can STORE reference to functions.
It might be difficult to understand why you would want to do it in this particular case, but, hey, printing "Hello world" also seems meaningless :)
You are referring to an example in a tutorial so it is not strange that they are oversimplifying things. However, believe me, that in a real world there are many cases in which storing references to functions is very-very useful!
One obvious example is when you want to store reference to some completion handler which you want to execute at the end of some lengthy operation. And which can be different depending on the context from which you initiated this operation.
To answer your question, you are effectively returning the function itself, and not the result of calling that function. In this case, it lets you choose a function (using the switch statement) and evaluate it later. A helpful way to think about it is that functions are also a type of variable, and you can pass them around as well as evaluate them.
As a general stylistic thing, it's good practice to end each case with a break. It makes no difference here because return will also end the execution of the function, but without a break, all code after the correct case will be executed, not just the code within the correct case. Running into another case statement doesn't break out of the switch statement by itself.
Why are we not calling the methods?
Presumably, the method will be called later. The purpose of the switch statement is to return a function that can be used later.
What do they mean we are returning a reference to it? ... What do they mean by reference?
The "reference" language is a bit confusing - functions are reference types, but that isn't super important to what is going on. You can think of it as just returning a function.
The bottom line is that functions in swift can be used like any other type - they can be stored in variable or constants, they can be passed into a function as a parameter, and they can be returned from a function.
In this case, you have a function that is designed to return a function. If you want to obtain the mean, you pass the string "mean" and the function will return a new function that will obtain the mean when you call it.

What's the proper way to declare a field holding a function in dart?

Imagine a silly class like this:
class ConditionalWorker{
var validityChecker= (inputs)=>true;
ConditionalWorker(this.validityChecker)
...
Now my question is, what is the proper way of declaring the validityChecker field?
This tutorial suggests using typedefs. But that's not very practical. Firstly it's a chore to write a lot of typedefs that would only be used once. And secondly these typedefs show up and pollute the autocompletion of my IDE.
The var works best, with custom setters/constructor arguments to keep it always of a specific kind, but I know it's discouraged by the style guide.
I could do Function<bool> but that just a more glorified var and the amount of work is the same.
It's a shame because it's perfectly legal to have a function like this:
bool every(bool test(E element));
where the parameter is a very well defined function, but I can't have a field declared the same way:
bool test(E element);
But hopefully there is something just as good that I didn't figure out. Right?d
If you want a function type more specific than Function, you need a typedef.
If you don't like to have named typedefs for every return type, you can define generic function types yourself.
typedef R function0<R>();
typedef R function1<S,R>(S arg1);
typedef R function2<S,T,R>(S arg1. T arg2);
typedef R function3<S,T,U,R>(S arg1, T arg2, U arg3);
Then you can write:
function1<int,int> curryAdd(int x) => (int y) => x + y;
Or if function0 looks bad to you, you can name them NullaryFunction, UnaryFuncytion, BinaryFunction, TernaryFunction, or any other name that you like.
If Function<bool> is not specific enough (you also want to specify the number and type of the arguments you have to use typedefs. There are no other ways.
I'm not sure why you think it is not practical. If you want to specify the type for a field that references a value you have to use one of the existing classes or create a new one. It's the same for fields referencing functions.
With Dart 2 we can use inline function types and we need to use it instead of typedefs where possible.
With inline function types we now can define a function as a field or a property as simple as this:
final bool Function(E) test;

function return different objects

I have a function(myFunction) with parameter v, I hope it can return different object depend the value of v.
something like below:
-(NSString*)myFunction:(NSInteger)v;
-(NSNumber*)myFunction:(NSInteger)v;
Is it possible?
Welcome any comment
Thanks interdev
You can always return an id, but I think it could be confusing for whoever is using this function, as they wouldn't know what the function would return.
Depending on the context you're using the function, it would probably be better to simply have different functions
-(NSString*)myFunctionNSStringForNSInteger:(NSInteger)v;
-(NSNumber*)myFunctionNSNumberForNSInteger:(NSInteger)v;
If you want it to do different things depending on the value of v why not just switch on the value of v and call the relevant function with the required return type?
You can e.g. declare the function to return NSObject. Then you can return all kinds of objects that inherits from NSObject. When using the function you might have to check the type of the returned object, depending on what you want to do with the result.

When do I have to specify type <T> for IEnumerable extension methods?

I'm a bit confused about the use of all the IEnumerable<T> extension methods, intellisense is always asking for <T>, but I don't think it's necessary to specify <T> at all times.
Let's say I have the following:
List<Person> people = GetSomePeople();
How is this:
List<string> names = people.ConvertAll<string>(p=>p.Name).Distinct<string>().ToList<string>();
different from this:
List<string> names = people.ConvertAll<string>(p=>p.Name).Distinct().ToList();
I think the two lines of code above are sxactly the same, now the question:
How do I know when to specify <T> and when to skip it?
The simplest way is obviously to omit it and see if it compiles.
In practice, you can omit type parameters wherever they are inferred; and they can normally be inferred when they are used in the type of a method parameter than you specify. They cannot be inferred if they're used only in the return type of the method. Thus, for example, for Enumerable.Select<T>, T will be inferred from the type of first argument (which is of type IEnumerable<T>). But for Enumerable.Empty<T>(), will not be inferred, because it's only used in return type of the method, and not in any arguments (as there are none).
Note that the actual rules are more complex than that, and not all arguments are inferable. Say you have this method:
void Foo<T>(Func<T, T> x);
and you try to call it with a lambda:
Foo(x => x);
Even though T is used in type of argument here, there's no way to infer the type - since there are no type specifications in the lambda either! As far as compiler is concerned, T is the same type x is, and x is of type T...
On the other hand, this will work:
Foo((int x) => x);
since now there is sufficient type information to infer everything. Or you could do it the other way:
Foo<int>(x => x);
The specific step-by-step rules for inference are in fact fairly complicated, and you'd be best off reading the primary source here - which is C# language specification.
This feature is known as type inference. In your example, the compiler can automatically determine the generic argument type implicitly for you because in the method call to ConvertAll, the parameter lambda returns a string value (i.e. Name). So you can even remove the <string> part of ConvertAll call. The same is with Distict(), as ConvertAll returns a List<string> and the compiler can declare the generic argument for you.
As for you answer, when the compiler can determine the type itself, the generic argument is redundant and unnecessary. Most of the times, the only place where you need to pass the generic argument is the declaration, like, List<string> list = new List<string>();. You can substitute the first List<string> with var instead or when you are using templates as parameters in lambdas too.