Function evaluation - function

In this question Invoking function which accept functions as parameters is this also a valid explanation of why the code does not compile?
funParam(3) is a valid invocation but fun(funParam(3)) is not. funParam(3) is not evaluated until compilation so the compiler cannot accept this as a valid parameter.
I think I'm confused as it's common practice to pass parameters to functions pre compilation but it is not valid to pass functions which contain parameters to functions pre compilation?

I think you may be confusing a couple concepts.
It's worth thinking about why a function might take another function as a parameter. Given fun: (Int => Int) => Int (a function that takes a function of Int => Int as a parameter and returns an Int), presumably, fun is planning to pass an Int to its argument, and return some modified version of the result. This pattern is used frequently in functional programming, like when we pass functions to map or reduce that operate on values inside a collection. The argument of type Int => Int to fun is essentially a calculation with a "hole" in it, and it's counting on fun or some other operation to provide the Int it needs to be fully evaluated.
funParam(3) doesn't have any unspecified variables, and it will be evaluated immediately whenever it's referred to. That's why the type of funParam(3) is Int. Sure, funParam itself is Int => Int, but since you've given it the Int parameter 3, the type of the whole expression is just the return type: Int.

Given
def funParam(i: Int): Int = ...
You can treat the methodfunParam as a function with type Int => Int
But funParam(3) is not a function, it is a concrete value--an Int, and therefore not Int => Int
So you cannot pass an Int to a method that is expecting Int => Int.

The reason is because fun expects Int => Int as an argument, but funParam(3) is not of that type. Its type is Int.

Related

Is a function just a type like any other type? [duplicate]

When I define a custom type, it seems that the type of the underlying type makes a difference about whether I can pass it to a function as is or I need to convert it.
Question is:
Why does RuneFunc and StringMap work, but not Integer?
https://play.golang.org/p/buKNkrg5y-
package main
type RuneFunc func(rune) rune
type Integer int
type StringMap map[string]string
func main() {
//m := make(StringMap)
//mf(m)
var i Integer = 5
nf(i)
//var f func(rune) rune
//ff(f)
}
func mf(i map[string]string) {
}
func ff(i func(rune)rune) {
}
func nf(i int) {
}
Here, when I run this function called nf with Integer it complains although int is the underlying type. But when I call mf or ff they run successfully.
Integer and int
int and your new type Integer are 2 different, distinct types. Where Integer is expected, you have to pass a value of type Integer.
If you have an Integer value, you may use a simple type conversion to make it a value of type int, because the underlying type of Integer is int:
var i Integer = 5
nf(int(i))
What may be confusing and interesting at the same time is that you are allowed to pass an untyped constant without conversion:
nf(5)
Try these on the Go Playground.
The reason for this is in the Spec: Assignability:
A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:
[...]
x is an untyped constant representable by a value of type T.
5 is an untyped constant which is representable by a value of type int because the untyped constant 5 has a default type int, so it is representable by a value of type Integer (which has the same default type).
If you check the other assignability rules (not included in above quotation), none of them match the case where you attempt to pass a value of Integer for the parameter of type int, so that's not allowed.
See related question: Golang: Creating a Constant Type and Restricting the Type's Values
RuneFunc and func(rune) rune
The difference between this case and the previous one (Integer and int) is that int is a named type and func(rune) rune is not.
And there's an assignability rule which allows this:
x's type V and T have identical underlying types and at least one of V or T is not a named type.
So in this case:
var f RuneFunc
ff(f)
f is a named type, but the parameter type of ff() is func(rune) rune which is unnamed, so the assignment is allowed.
Go has a strict type system. Just because your type is merely an alias for int doesn't mean you can interchange the two freely, you'll still have to do a type conversion. Below is a working version of your main, here's the code on play ground: https://play.golang.org/p/BDTXnnG9Lg

Lambdas assigned to variables in Kotlin. Why?

I noticed that I get the same effect if I define this trivial function:
fun double ( i: Int ) = i*2
and if I define a variable and assign a lambda (with an identical body) to it:
var double = { i : Int -> i*2 }
I get the same result if I call double(a) with either declaration.
This leaves me confused. When is it needed, recommended, advantageous to define a variable as a lambda rather than define a function to it?
When is it needed, recommended, advantageous to define a variable as a lambda rather than define a function to it?
Whenever you have the choice of either, you should use a fun declaration. Even with a fun you can still get a first-class callable object from it by using a function reference.
On the JVM, a fun is significantly more lightweight, both in terms of RAM and invocation overhead. It compiles into a Java method, whereas a val compiles into an instance field + getter + a synthetic class that implements a functional interface + a singleton instance of that class that you must fetch, dereference, and invoke a method on it.
You should consider a function-typed val or var only when something is forcing you to do it. One example is that you can dynamically replace a var and effectively change the definition of the function. You may also receive function objects from the outside, or you may need to comply with an API that needs them.
In any case, if you ever use a function-typed property of a class, you'll know why you're doing it.
First, if I understand you right, your question is "Why are functions first-class citizens in Kotlin -- And when to use them as such?", right?
Kotlin functions are first-class, which means that they can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions. You can operate with functions in any way that is possible for other non-function values. (see here)
As stated in the docs, one use case are higher-order functions. As a first step, I will leave the wikipedia link here: https://en.wikipedia.org/wiki/Higher-order_function
Basically, a higher-order function is a function that takes functions as parameters, or returns a function.
This means that a higher-order function has at least one parameter of a function type or returns a value of a function type.
Following a short example of a higher-order function that receives a parameter of function type (Int) -> Boolean:
fun foo(pred: (Int) -> Boolean) : String = if(pred(x)) "SUCCESS" else "FAIL"
This higher-order function can now be called with any (Int) -> Boolean function.
The docs also state ... [can be used] in any way that is possible for other non-function values.
This means that you can, for example, assign different functions to a variable, depending on your current context.
For example:
// This example is verbose on purpose ;)
var checker: (Int) -> Boolean
if (POSITIVE_CHECK) {
checker = { x -> x > 0 } // Either store this function ...
} else {
checker = { x -> x < 0 } // ... or this one ...
}
if (checker(someNumber)) { // ... and use whatever function is now stored in variable "checker" here
print("Check was fine")
}
(Code untested)
You can define variable and assign it lambda when you want change behaviour for some reason. For example, you have different formula for several cases.
val formula: (Int) -> Int = when(value) {
CONDITION1 -> { it*2 }
CONDITION2 -> { it*3 }
else -> { it }
}
val x: Int = TODO()
val result = formula(x)
If you simply need helper function, you should define it as fun.
If you pass a lambda as a parameter of a function it will be stored in a variable. The calling application might need to save that (e.g. event listener for later use). Therefore you need to be able to store it as a variable as well. As said in the answer however, you should do this only when needed!
For me, I would write the Lambda variable as followed:
var double: (Int) -> Int = { i -> //no need to specify parameter name in () but in {}
i*2
}
So that you can easily know that its type is (i: Int) -> Int, read as takes an integer and returns an integer.
Then you can pass it to somewhere say a function like:
fun doSomething(double: (Int) -> Int) {
double(i)
}

why declaration of methods in different style different results in scala

Below are two methods that are declared in different style. Both are doing the same work. I am wondering, why
different syntax is required to check type of function (yellow
block)
different syntax is required to call function (green block)
declaration of both methods on scala repl gives different results
(red block)
Also, please suggest, which one is the preferred way to declare
methods or are there any special use cases for both the styles of
method declaration?
Edit 1:
Below are the commands from screenshot :-
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_79).
Type in expressions to have them evaluated.
Type :help for more information.
scala> def add(x:Int, y :Int): Int = {x+y}
add: (x: Int, y: Int)Int
scala> def sum = (x:Int, y:Int) => {x+y}
sum: (Int, Int) => Int
scala> :t add
<console>:12: error: missing arguments for method add;
follow this method with `_' if you want to treat it as a partially applied function
add
^
scala> :t add(_, _)
(Int, Int) => Int
scala> :t sum
(Int, Int) => Int
scala> add
<console>:12: error: missing arguments for method add;
follow this method with `_' if you want to treat it as a partially applied function
add
^
scala> add(_, _)
res1: (Int, Int) => Int = <function2>
scala> sum
res2: (Int, Int) => Int = <function2>
Edit 2:
#Shadowlands
i have read on dzone, that states "when a function is expected but a method is provided, it will be automatically converted into a function. This is called the ETA expansion.".
Now, if ETA takes care to convert your methods to function. Is it really required to use sum style, because it looks like an additional overhead of Function<> object.
Simply put, add is a function that takes two Int arguments and returns an Int result, while sum is a 0-argument function that returns a new function that, in turn, takes two Int arguments and returns an Int result. Indeed, sum could readily be defined as:
def sum = add _
As to which way to define your functions, this depends on how it is to be used. Generally, use the add style most of the time, as it is easier to understand and work with. If, however, you will be passing the function as an argument to another function, then the sum-style formulation can be more convenient and may convey more of your intent on how the function is expected to be used.
This is how REPL is implemented. The code that you type is wrapped in object. Thus your def add becomes method of this object, while def sum is a method that returns Function. When you are addressing add like this: add(_, _) you are addressing method, while when you are addressing sum as sum you are addressing result of sum's execution, which is function.
Differences between methods and functions are described here.
PS. Try to check the type of sum _

scala implicit class method type mismatch in reduce vs non-implicit method with function currying

Problem:
Something about implicit class, confuses reduce().
When inside implicit class, compiler complains on reduce() second parameter.
but when same code is inside non-implicit method it compiles and works fine.
What am I missing about implicit classes?
Code:
object ImpliCurri {
implicit class MySeq[Int](val l: Seq[Int]) {
//not compiling
final def mapSum(f:Int=>Int):Int = {
l.map(x=>f(x)).reduce(_+_)
//compile error on reduce: Type mismatch. Expected String, fount Int
}
}
// works fine
def mySum(l:Seq[Int], f:Int=>Int):Int = {
l.map(x=>f(x)).reduce(_+_)
// compiles and works no issues
}
}
You need to get rid of the type parameter Int. Int in the case of the implicit class is not actually the type Int, but instead it's a free type parameter that's shadowing the name of Int.
The reason for the cryptic compiler error is that the compiler is inferring the type Any from the lambda _ + _ (since the type parameter could be anything), and assuming the + will come from a toString on type Any. If you replace Int with T in the class declaration, you'll see the error is the same.
This will work:
implicit class MySeq(val l: Seq[Int]) {
final def mapSum(f: Int => Int): Int = {
l.map(x => f(x)).reduce(_ + _)
}
}
It doesn't actually have anything to do with implicits. You get the same error if it's just a regular class.
The reason is that you have declared a generic type: MySeq[Int] that just happens to be called Int. So when you say f: Int => Int you think "Oh, that's an integer" and the compiler thinks, "Oh, that means you could fill in any type there!". (Replace all your Ints with A and it would work the same.)
Now the compiler is in a bind. What + can you apply to any pair of types? Well, you can convert anything to a String, and + is defined on a String. So you get a very misleading error message when the compiler realizes that this approach won't work.
Just drop the [Int] and all your Ints will actually mean what you think they mean, and the implicit class version will work fine.
Replace MySeq[Int](val l: Seq[Int]) with MySeq(val l: Seq[Int]).
Explanation of the compiler message:
The MySeq[Int] part defines an abstract type parameter for class MySeq named Int, which is (automatically) a subclass of Any and shadows the actual scala.Int. Then the compiler tries to call + method of an instance of Any. It sees a declaration of an implicit class scala.Predef.any2stringadd, which has a method with signature def +(other: String): String, so the compiler thinks the second parameter to + should be a String.

Function objects in C++ (C++11)

I am reading about boost::function and I am a bit confused about its use and its relation to other C++ constructs or terms I have found in the documentation, e.g. here.
In the context of C++ (C++11), what is the difference between an instance of boost::function, a function object, a functor, and a lambda expression? When should one use which construct? For example, when should I wrap a function object in a boost::function instead of using the object directly?
Are all the above C++ constructs different ways to implement what in functional languages is called a closure (a function, possibly containing captured variables, that can be passed around as a value and invoked by other functions)?
A function object and a functor are the same thing; an object that implements the function call operator operator(). A lambda expression produces a function object. Objects with the type of some specialization of boost::function/std::function are also function objects.
Lambda are special in that lambda expressions have an anonymous and unique type, and are a convenient way to create a functor inline.
boost::function/std::function is special in that it turns any callable entity into a functor with a type that depends only on the signature of the callable entity. For example, lambda expressions each have a unique type, so it's difficult to pass them around non-generic code. If you create an std::function from a lambda then you can easily pass around the wrapped lambda.
Both boost::function and the standard version std::function are wrappers provided by the li­brary. They're potentially expensive and pretty heavy, and you should only use them if you actually need a collection of heterogeneous, callable entities. As long as you only need one callable entity at a time, you are much better off using auto or templates.
Here's an example:
std::vector<std::function<int(int, int)>> v;
v.push_back(some_free_function); // free function
v.push_back(&Foo::mem_fun, &x, _1, _2); // member function bound to an object
v.push_back([&](int a, int b) -> int { return a + m[b]; }); // closure
int res = 0;
for (auto & f : v) { res += f(1, 2); }
Here's a counter-example:
template <typename F>
int apply(F && f)
{
return std::forward<F>(f)(1, 2);
}
In this case, it would have been entirely gratuitous to declare apply like this:
int apply(std::function<int(int,int)>) // wasteful
The conversion is unnecessary, and the templated version can match the actual (often unknowable) type, for example of the bind expression or the lambda expression.
Function Objects and Functors are often described in terms of a
concept. That means they describe a set of requirements of a type. A
lot of things in respect to Functors changed in C++11 and the new
concept is called Callable. An object o of callable type is an
object where (essentially) the expression o(ARGS) is true. Examples
for Callable are
int f() {return 23;}
struct FO {
int operator()() const {return 23;}
};
Often some requirements on the return type of the Callable are added
too. You use a Callable like this:
template<typename Callable>
int call(Callable c) {
return c();
}
call(&f);
call(FO());
Constructs like above require you to know the exact type at
compile-time. This is not always possible and this is where
std::function comes in.
std::function is such a Callable, but it allows you to erase the
actual type you are calling (e.g. your function accepting a callable
is not a template anymore). Still calling a function requires you to
know its arguments and return type, thus those have to be specified as
template arguments to std::function.
You would use it like this:
int call(std::function<int()> c) {
return c();
}
call(&f);
call(FO());
You need to remember that using std::function can have an impact on
performance and you should only use it, when you are sure you need
it. In almost all other cases a template solves your problem.