Functional parameters in Go functions - function

Is there a way to pass a function(which can be generic) to another function?
I know that with known input types and return types we can pass a function but a generic approach is needed

When reading the Go2 proposal on generic: "Type Parameters - Draft Design", I am not sure you would be able to pass as parameter a generic function without explicitly specify the type used by said function
See "Instantiating a function"
Go normally permits you to refer to a function without passing any arguments, producing a value of function type.
You may not do this with a function that has type parameters; all type arguments must be known at compile time.
That said, you can instantiate the function, by passing type arguments, but you don't have to call the instantiation. This will produce a function value with no type parameters.
// PrintInts is type func([]int).
var PrintInts = Print[int]

Related

Check if a function takes specified arguments in Rust

Is there a way in a where clause in Rust to check if a function passed as a parameter takes specified arguments?
If you're defining a function that takes a function argument, that argument has a very specific type associated with it that dictates the arguments. You cannot call that function with something that doesn't match, it just won't compile.
If you're thinking in terms of dynamic languages where the arguments are somewhat subjective, you're assuming you can make a mistake here and call it incorrectly. You can't. It's strictly disallowed.

How to do type checking for a recursive function with no explicit return type?

I am writing a language where functions are not typed. Which means I need to infer the return type of a function call in order to do type checking. However when somebody writes a recursive function the type checker goes into an infinite recursion trying to infer the type of the function call inside the function body.
The type checker does something like this:
Infer the types of the function call actual arguments.
Create a mapping of the actual argument types to the formal arguments.
Use the mapping to annotate types on the arguments used inside the function body.
Infer and return the return type of the function body.
Step 4 tries to then infer the type of the function call inside the function body, which calls the same type checker function again, causing an infinite recursion.
An example of a recursive function that gives me this problem:
function factorial(n) = n<1 ? 1 : n*factorial(n-1); // Function definition.
...
assert 24 == factorial(4); // Function call expression usage example.
How can I solve this problem without going in to an infinite recursion loop? Is there a way to infer the type of the recursive function call without having to go into the body again? Or some clean way to infer the type from context?
I know the easy solution might be to add types annotations to functions, this way the problem is trivial, but before doing that I want to know if there is a way to solve this without resorting to that.
I'd also like for the solution to work for mutual recursion.
Type inference can vary a lot depending on the language's type system and on what properties you want to have in terms of when annotations are needed. But whatever your language looks like, I think there's one seminal case you really should read about, which is ML. ML's type inference holds a nice sweet spot where it all fits together in a relatively simple paradigm. No type annotations are needed, and any expression has a single most general type (this property is called principality of typing).
ML's type system is the Hindley-Milner type system, which has parametric polymorphism. The type of an expression is either a specific type, or “any”. More precisely, the type constructor of an expression is either a specific type constructor or “any”, and type constructors can have arguments which themselves either have a specific type constructor or “any”. For example, the empty list has the type “list of any”. Two expressions that can have “any” type in isolation may be constrained to have the same type, whatever it is, so “any” is expressed with variables. For example, function list_of_two(x, y) = [x, y] (in a notation like your language) constrains x and y to have the same type, because they're inserted in the same list, but that type can be any type, so the type of this function is “take any two parameters of the same type α, and return a value of type list of α”.
The basic type inference algorithm for Hindley-Milner is algorithm W. At its core, it works by giving each subexpression a type that's a variable: α₁, α₂, α₃, … Programming language constructions then impose constraints on those variables. For example, if a list contains two elements of types α₁ and α₂ and the list itself has the type α₃, this constraints α₁ = α₂ and α₃ = list of α₁. Putting all these constraints together is a unification problem.
The constraints are based on a purely syntactic reading of the program. If there's a recursive call, you don't need to know the type of the function: it just means that there's a constraint that the variable for the return type of the function is the same as the type at its point of use. That's just one more equation to add to the set of constraints.
I left out an important aspect of ML which is that an expression's type can be generalized: an expression can be used with different types at different places. This is what allows polymorphism. For example,
let empty_list = [] in
(empty_list # [3]), (empty_list # ["hello"])
is a valid program where empty_list is used once with the type “list of integers” and once with the type “list of strings”. The type of empty_list is “for any α, list of α”: that's parametric polymorphism. Generalization adds some complexity to the algorithm, but it also removes complexity elsewhere, because that's what allows principality. Without it, let empty_list = [] in … would be ambiguous: empty_list would have to have some type, but there's no way to know what type without analyzing …, and then when you do analyze the … above you'd need to make a choice between integer and string.
Depending on your language's type system, ML and algorithm W may be directly reusable or may just provide some vague inspiration. But the principle of using variables during the inference, and progressively constraining these variables, is very general.

What happens if we add different parameter type in a function interface of a lambda expression?

I am learning lambda expressions. I came across a scenario that can be understood by the below code:
Function<Integer,String> fn = (String s)->s;
In the above statement of lambda expression, I know that a function accepts an argument and returns the mentioned type. But why do we mention the argument type ,(here, it is Integer) on the part "Function" whereas the arguments are to be passed inside the "()". I know it is part of the syntax, but I just want to understand the point where it may be useful. It runs even if we pass an different argument type(String)?
First of all the Function you have written is wrong. It should be corrected as below.
Function<Integer, String> fn = s -> String.valueOf(s);
You can't state a different data type as above, only thing you can state is an integer. Any other data type as the input parameter would result in a compilation failure. The data type of the lambda function parameter is optional and is inferred by the compiler.

Is C++ function belonging to "callable type"

The C++11 standard says:
20.8.1 Definitions [func.def]
1 The following definitions apply to this Clause:
2 A call signature is the name of a return type followed by a parenthesized comma-separated list of zero or
more argument types.
3 A callable type is a function object type (20.8) or a pointer to member.
4 A callable object is an object of a callable type.
So my understanding is, a function is an instance of function type, so function is not "callable type". But definitely we can call functions.
This definition is a bit weird to me. Where did I get wrong?

What are the definitions of named method and named function?

I have read the question Difference between method and function in Scala and many articles about differences between method and function. I got a feeling that a 'method' is just a "named function" defined as a method in a class, a trait or an object. A 'function' represents things like the "anonymous function" or "function literal" or "function object" in those articles. An evidence can be found in the book Programming in Scala http://www.artima.com/shop/programming_in_scala_2ed , page 141, section 8.1, "The most common way to define a function is as a member of some object. Such a function is called a method."
However, when I checked the Scala Language Reference http://www.scala-lang.org/docu/files/ScalaReference.pdf, there are concepts like named method. In page 91, Section 6.20 Return expressions: "A return expression return e must occur inside the body of some enclosing named
method or function." You can also find the term "named function" in the same page and other places.
So my question is, in Scala, do method, named method, and named function refer to the same concept? Where do you get the definition of named function?
In code List(1, 2).map(_ + 1), the original expression _ + 1 is a named method, then the method is converted into a function. What kind of function, anonymous function, function object, named function?
In my understanding, Scala only has two types of function: a named function that is a method; an anonymous function that is a function literal. Function literal is compiled into a function object of trait FunctionN for it to be used in the pure object-oriented world of Scala.
However, for a regular named funciton/method such as _ + 1 in the above code, why does Scala transform it into another function object?
At the language level, there are only two concepts,
Methods are fundamental building blocks of Scala. Methods are always named. Methods live in classes or traits. Methods are a construct native to the JVM, and thus are the same in both Scala and Java. Methods in Scala (unlike functions) may have special features: they can be abstracted over type parameters, their arguments can have default values or be implicit, etc.
Function objects are just instances of a function trait (Function1, Function2, ...). The function is evaluated when the apply method on the function object is called. There is special syntax for defining unnamed "anonymous" functions (aka, "function literals"). A function is just a value, and as such can be named (e.g., val f: (Int => Int) = (x => x)). The type A => B is shorthand for Function1[A, B].
In the linked SO question, it was mentioned that some references (like the Scala spec) use the word "function" imprecisely to mean either "method" or "function object". I guess part of the reason is that methods can be automatically converted to function objects, depending on the context. Note, however, that the opposite conversion wouldn't make sense: a method is not a first-class value that lives on the heap with its own independent existence. Rather, a method is inextricably linked to the class in which it is defined.
The answers to the linked question cover this fairly well, but to address your specific queries:
method => The thing you define with the def keyword
named method => The same, all methods have names
named function => a function that has been assigned to a value, or converted from a method. As contrasted with an anonymous function.
The difference between a method and a Function is somewhat like the difference between an int primitive and a boxed Integer in Java.
In general discussion, it's common to hear both described as being "integers". This normally isn't a problem, but you must take care to be precise wherever the distinction is relevant.
Likewise, a method will be automatically converted to a Function (and therefore an object) when your program demands it, much like boxing a primitive. So it's not entirely wrong to refer to a method as being a function.
UPDATE
So how does it work?
When you attempt to pass a method as the argument to e.g. List[A].map, the compiler will generate an inner class (with a synthetic name) that derives Function1[A,B], and an apply method that delegates to the method you originally supplied. An instance of this will then be passed as the actual argument.